list_of_nums = list(map(int, input().split()))
list_ans = [-1 for element in (list_of_nums)]
list_ans_2 = [-1 for element in (list_of_nums)]
stack = []
for i in range(len(list_of_nums)):
while ((len(stack) > 0) and (list_of_nums[stack[-1]] < list_of_nums[i])):
j = stack.pop()
list_ans[j] = i
stack.append(i)
stack = []
for i in range(len(list_of_nums) - 1, -1, -1):
while ((len(stack) > 0) and (list_of_nums[stack[-1]] < list_of_nums[i])):
j = stack.pop()
list_ans_2[j] = i
stack.append(i)
for i in range(len(list_ans)):
if (list_ans[i] == -1 and list_of_nums[list_ans[i]] != max(list_of_nums) and list_ans_2[i] != -1 and (list_ans[i] > list_ans_2[i])):
list_ans[i] = list_ans_2[i]
print(list_ans)
You are given a list of integers and then you should print another list containing the closest number (left or right) to the element of the original list that is strictly greater than it.
My logic with this code is that I have a list of answer that gets filled with closest bigger number on the right and then I get another list getting closest bigger number on the left.
I then compare the two lists and if the bigger number from right to left is closer than the bigger on from left to right I make that the bigger number in the list of answers