Monotonic Stack/Queue

Published by

on

Definition

  • Stack or Queue which is in ascending/descending order
    • Always sorted

Applicable Problems

  • Finding the “next” element based on some criteria,
    • ex) Finding the next greater element.
  • When you have a dynamic window of elements and need to maintain maximum or minimum element as the window changes

Pseudo Code

Given an integer array nums

stack = []
for num in nums:
    while stack is not empty:
        if (stack.top meet condition): // ex) Descending order: (num > top)
            stack.pop()            
            // Add logic
        else:
            break

    // Between the above and below lines, do some logic depending on the problem
    stack.push(num)

Leave a comment

Previous Post
Next Post