🌊

Monotonous Stack

Targets: for each item in a list, find its nearest bigger / smaller element on the right-hand side.
Example:
input a list [73, 74, 75, 71, 69, 72, 76, 73], output a list which show for each item, the interval between it and its nearest bigger element on the rigth-hand side. If there is no bigger elements on the right-hand side for the element, the value is 0.
def solution(tlist): stack = [] res = [0] * len(tlist) for i in range(len(tlist)): while len(stack) and tlist[stack[-1]] < tlist[i]: res[stack[-1]] = i - stack[-1] stack.pop() stack.append(i) return res
Problems:

Loading Comments...