Usually things related to immediate paring (valid parentheses, reverse polish notation); these are relatively simple as all you do is append or remove immediately at relatively simple conditions (comparing with existing mapping or from within the stack itself).
The more interesting form of the problem is monotonic stack; monotonic stacks involve some form of indexing (most of the time anyway). If a problem mentions next greater or next smaller/lesser alongside overlap or collide, chances are, it’s a monotonic stack problem.
The pattern (monotonic stack) goes as such,
# this will hold the indicesstack = []result = [] # [0] * len(argument) <- depends on the problemfor index, value in enumerate(argument): # > for greater than < for less than while stack and value > argument[stack[-1]]: # .pop() the latest added index (stack) # logical processes goes here # append the latest index stack.append(index)return result
stack = []result = [0] * len(temperatures)for index, temperature in enumerate(temperatures): while stack and temperature > temperatures[stack[-1]]: prev = stack.pop() result[prev] = index - prev stack.append(index)return result