Skip to content

Latest commit

 

History

History
43 lines (33 loc) · 1.7 KB

monotonic_stack.md

File metadata and controls

43 lines (33 loc) · 1.7 KB

Monotonic Stack

  • A monotonic stack is a special form stack inside which all elements are sorted in either ascending or descending order

Template

def monotonic_stack(nums):
    """An increasing monotonic stack, all elements are sorted in ascending order"""

    stack = []
    res = [-1] * len(nums)

    # Template for descending traversal
    for i in range(len(nums)-1, -1, -1):
        while stack and nums[stack[-1]] <= nums[i]:
            stack.pop()   # Remove existing element that is smaller than incoming element
        if stack:
            res[i] = nums[stack[-1]]
        stack.append(i)  # use for next iteration

    # # Template for ascending traversal
    # for i in range(len(nums)):
    #     while stack and (nums[stack[-1]] < nums[i]):
    #         res[stack.pop()] = nums[i]
    #     stack.append(i)
    return res

Reference:

Practice: