loading...

re: Daily Challenge #238 - One is the Loneliest Number VIEW POST

FULL DISCUSSION
 

Here is a Python solution,


def lonelyNum(number : int) -> int:
    digits = list(map(int, str(number)))
    loneliest = digits[0]
    min_loneliness = min_friends = float('inf')

    for i in range(len(digits)):
        left_friends = digits[max(0,i-digits[i]):i]
        right_friends = digits[i+1:min(len(digits),i+1+digits[i])]

        loneliness = sum(left_friends+right_friends)
        friend_count = len(left_friends+right_friends)

        if(loneliness < min_loneliness):
            loneliest = digits[i]
            min_loneliness = loneliness
            min_friends = friend_count
        elif(loneliness == min_loneliness and friend_count < min_friends):
            loneliest = digits[i]
            min_friends = friend_count

    return loneliest

Outputs,

print(lonelyNum(34315)) # output -> 1
print(lonelyNum(23456)) # output -> 2
print(lonelyNum(42435)) # output -> 2
code of conduct - report abuse