Keywords and Patterns

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 indices
stack = []
result = [] # [0] * len(argument) <- depends on the problem
 
for 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
 

Examples

Daily Temperatures

Problem here: Daily Temperatures

Problems