Search⌘ K
AI Features

Common Stack Patterns

Explore common stack patterns important for JavaScript coding interviews. Understand how to apply the monotonic stack for array problems and iterative depth-first traversal for tree or graph challenges. Learn to choose the right pattern for efficient problem solving and avoid pitfalls like incorrect stack processing or traversal order.

Recognizing a stack as the right data structure is only the first step. The next step is knowing which pattern to apply. This lesson covers the two most important stack patterns in coding interviews: the monotonic stack and iterative depth-first traversal. Each solves a specific class of problems that would otherwise require significantly more expensive approaches.

Monotonic stack

The monotonic stack pattern maintains a stack in sorted order, either strictly increasing or strictly decreasing, as we scan through an array. In JavaScript, this stack is usually just an array used with push and pop. When an incoming element violates the sort order, we pop elements off the stack until the order is restored, processing each popped element as we go. This gives us O(n)O(n) solutions to problems that would otherwise require O(n2)O(n^2) ...