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
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Here is a Python solution,
Outputs,