Some work finishes in the reverse order it started. Think of nested brackets, undo, or “the latest thing I haven’t finished yet”. A stack is the data structure for that kind of work, and you’ll often need one even when the problem statement never mentions it.

Half of this topic’s problems also need a variant called the monotonic stack. It finds the nearest bigger or smaller element for every position in one pass, so it gets a second module of its own.

Stack builds on Arrays & Hashing and sits next to Two Pointers. It’s a leaf topic, which means no later topic depends on it. Still, you’ll meet the same structure again: the call stack behind every recursive tree and graph traversal later in the series is a stack.

How to use this post: the method. The checkpoints don’t show answers on the page. Work each one out yourself first, then open the linked chat to have your answer checked.

Stacks

Foundation

Think of a stack of plates. You put a plate on top, and you take a plate off the top. You never pull one out of the middle. That one restriction is what makes it a stack. The last plate in is the first plate out, which is why it’s called last in, first out (LIFO).

For interviews, a more useful picture is a to-do list with a strict rule: you must finish the newest item before you can get back to the older ones. Some problems have this shape: “the next thing I need to deal with is the most recent thing I haven’t dealt with yet.” In those problems, a stack holds exactly the unfinished items, already in the order you’ll need them.

A stack solves three families of problems:

  • Nesting. Inner things must close before outer things. Directories, function calls, and anything with an opening and a matching close all work this way.
  • Most recent first. An action applies to the latest item still waiting. Undo, backspace and “cancel the previous one” are examples.
  • Reversal. Push a sequence onto a stack, pop it all off, and it comes back reversed.

In Part 2 we saw that a dynamic array can append and pop at its end in O(1) amortized time. (Amortized means averaged over many operations: an occasional append is slow, but the average stays O(1).) A stack is just a dynamic array that you promise to touch only at that end. So in Python you don’t need a stack class. A list already is one.

Operation Python Cost
push stack.append(x) O(1) amortized (recalled)
pop stack.pop() O(1) (recalled)
peek at top stack[-1] O(1)
is empty? not stack O(1)
size len(stack) O(1)

Using the wrong end is expensive. stack.pop(0) and stack.insert(0, x) each have to shift every other element over by one, so each costs O(n) (recalled). If you ever need to work at both ends, use collections.deque instead. That’s no longer a stack.

Mechanics

The worked example for this module is simplifying a Unix-style path. Given "/a/b/../c/./d/..", return the canonical path: the same location written in its simplest form. The rules are:

  • A name means “go into that directory”.
  • .. means “go up one level”.
  • . means “stay here”.
  • Repeated slashes mean nothing.

Step by step:

  1. Split on /: ['', 'a', 'b', '..', 'c', '.', 'd', '..']. The empty strings come from the leading slash. Any // would produce one too.
  2. Walk the parts from left to right. Keep a stack of directory names, going from the root down to the directory you’re currently in.
  3. For a name, push it. You went one level deeper.
  4. For .., pop. You left the current directory.
  5. For . or an empty part, do nothing.
  6. At the end, read the stack from bottom to top. That’s the path.

The invariant. An invariant is a fact that stays true at every step of a loop. Here it is: after each part, the stack holds exactly the directories from the root to the current directory. The root is at the bottom and the current directory is on top.

Why popping is safe. .. can only ever mean “leave the directory I’m in right now”. And the directory you’re in right now is always the top of the stack. After a and b, the stack is [a, b]. The .. has to remove b, never a, because you can’t leave a while you’re still inside b.

That’s what nesting means. The newest unresolved item is the only one that can be resolved next. A stack keeps that item on top, where you can reach it in O(1).

The boundary case. At the root the stack is empty, and .. goes nowhere. So "/../x" is just "/x". That’s why the pop needs a guard. Without one, Python raises IndexError on [].pop() (recalled).

Diagram

The directory stack after each part of /a/b/../c/./d/..Eight panels. '' skip: empty. 'a' push: [a]. 'b' push: [a, b]. '..' pops b: [a]. 'c' push: [a, c]. '.' skip: [a, c]. 'd' push: [a, c, d]. '..' pops d: [a, c]. Result /a/c. Green marks the name just pushed; a red dashed box is the name a '..' popped.simplify_path("/a/b/../c/./d/.."): one panel per part of the split'' (empty)skip'a'pusha'b'pushab'..'pop 'b'ab'c'pushac'.'skipac'd'pushacd'..'pop 'd'acdread bottom to top: "/" + "a/c" = "/a/c"

Look at the two .. panels. Each one removes the most recent name that’s still on the stack: first b, then d. Neither one ever touches a.

Implementation

def simplify_path(path: str) -> str:
    stack = []  # directory names from the root (stack[0]) to the current directory (stack[-1])
    for part in path.split("/"):
        # "/a/b/../c/./d/..".split("/") -> ['', 'a', 'b', '..', 'c', '.', 'd', '..']
        if part == "" or part == ".":
            # "" comes from the leading "/" and from any "//"; "." means "stay here".
            # Neither changes the current directory, so the stack is left alone.
            continue
        if part == "..":
            # ".." leaves the current directory, which is stack[-1]:
            # with stack == ['a', 'b'], ".." must drop 'b', leaving ['a'].
            # With an empty stack we are at the root, and "/../x" must give "/x",
            # so skip the pop (recalled: [].pop() raises IndexError).
            if stack:
                stack.pop()
            continue
        stack.append(part)  # a real name: one level deeper, so it becomes the new top
    # stack is ordered root -> current, so joining bottom to top rebuilds the path.
    # For the example the final stack is ['a', 'c'] -> "/a/c".
    return "/" + "/".join(stack)

Here is what it returns for the worked example and some edge cases:

Input Output
"/a/b/../c/./d/.." "/a/c"
"/../x" "/x"
"/" "/"
"/home//foo/" "/home/foo"
"/a/../../b/./c/" "/b/c"

Complexity, with n = len(path):

  • O(n) time. The split and the join are each O(n). Each part is pushed at most once and popped at most once.
  • O(n) extra space, for the list of parts and the stack.

Recognition

These are the signals that a stack is the right tool:

  • The input has nesting or matching. Something opens, something later closes it, and the innermost one closes first.
  • An operation acts on the most recent item still waiting. Look for words like “undo”, “cancel the previous”, “delete the last” or “combine the last two”.
  • You scan left to right, and each new element does one of two things. Either it resolves some earlier element that was waiting, or it joins the waiting set itself.
  • A recursive solution exists and you want an iterative one. Recursion uses the call stack behind the scenes, and that’s a stack. You can keep one yourself instead.

When not to use one:

  • You need the oldest waiting item first, as in arrival order or level-by-level processing. That’s a queue.
  • You need the smallest or largest of everything waiting, not the newest. That’s a heap (Heap / Priority Queue). If nothing is ever removed, a single running variable is enough.
  • You need to remove from both ends. That’s a deque.

In this topic’s list, the signals are easy to spot. Valid Parentheses has nesting. Evaluate Reverse Polish Notation has operators that act on the most recent operands. Min Stack asks you to build on the stack interface itself.

Pitfalls

  • Popping or peeking on an empty stack. Always guard. Write if stack: before stack.pop(). In a loop, write while stack and stack[-1] .... If the stack is empty, the and stops early, so stack[-1] is never evaluated (recalled: and evaluates left to right and stops at the first falsy operand).
  • Forgetting what’s left at the end. If the stack isn’t empty when the loop ends, those items were never resolved. Decide on purpose what they mean. They might be the answer (like the path), a sign of an error, or items that should get a default value.
  • Using the wrong end. pop(0) quietly turns an O(n) algorithm into O(n²).
  • Pushing the wrong thing. Push whatever you’ll need at pop time. If you’ll later need a position or a distance, push the index, not the value.
  • Building strings inside the loop. Keep a list and "".join it once at the end. Don’t rebuild a string on every step.

Active Recall

1. In the worked example, what is the stack right after processing c, and why was a never popped even though two .. parts appeared?

2. What should "/a/../../b" return, and what line in the implementation makes that happen?

3. Why do we use append and pop() on the right end of the list instead of insert(0, x) and pop(0)? Both are “a stack”.

4. Suppose you only needed the depth of the final directory (for the example, 2), not its path. What could replace the stack?

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Kept for this topic. Every problem in this list arrives already labeled “Stack”. None of them makes you discover the plain push/pop habit from a statement that doesn’t name it. So without this checkpoint, you’d never practise this module’s mechanics on your own.

A string is reduced by repeatedly deleting two adjacent, equal characters, until no such pair remains. For "abbaca": delete "bb" to get "aaca", then delete "aa" to get "ca". Return the final string. The input can be up to 10⁵ characters. (The problem guarantees the final string is the same whichever pair you delete first.)

Before you open the chat, write down four things: the key observation, your approach, why it’s correct, and its complexity.

Work it out, then talk it through withChatGPT ↗Claude ↗

Transfer test

You’re building a text editor with three commands: type some text, undo the last change, redo the last undone change. Would you use a stack? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Monotonic Stack

Why it’s here: Daily Temperatures and Largest Rectangle In Histogram both need, for each element, the nearest element to one side that is bigger or smaller. The Stacks lesson alone doesn’t give you the pop rule that does this in O(n) instead of O(n²). The problems below also need it.

Foundation

Stand at the right end of a street of buildings and look left. A tall building hides every shorter building behind it.

Now say a tall building goes up at position i. Every shorter building to its left stops mattering to anyone standing further right. When they look left, they hit building i first and never see the shorter ones behind it.

A monotonic stack turns that picture into code. It’s a normal stack plus one rule: before pushing a new element, pop everything it hides. “Monotonic” means the values only ever go one way, and that’s what this rule gives you: what’s left on the stack is always sorted. It’s also exactly the set of elements that could still be the answer for something further right.

Here is the problem it solves. For each index i, find the nearest index j to one side where nums[j] is bigger (or smaller) than nums[i]. The brute force scans outward from each i until it finds one.

Why is that slow? Take an increasing array like [1, 2, 3, ..., n] and look left for something bigger. You never find one, so each i scans everything to its left. That’s 0 + 1 + … + (n−1) = n(n−1)/2 comparisons, which is O(n²).

Mechanics

Worked example: the previous greater element. For each i, find the index of the nearest j < i with nums[j] > nums[i] (strictly greater), or −1 if there isn’t one.

nums = [5, 3, 1, 3, 4, 2]

The stack holds indices, not values. For each index i with value x, the loop does three things:

  1. While the stack isn’t empty and the value at its top is ≤ x, pop.
  2. If the stack still isn’t empty, its top is the answer for i. Otherwise the answer is −1.
  3. Push i.

Two invariants (facts that stay true after every step) explain why this works.

Invariant 1 (the sorted part). The values at the stack’s indices are strictly decreasing from bottom to top. Step 1 removes everything ≤ x, so whatever is left on top is > x. Pushing x on top of it keeps the order strictly decreasing.

Invariant 2 (the shadow). Take two neighbouring stack entries, a below and b above. Every index strictly between a and b has a value ≤ nums[b]. Why? All those indices were already gone by the time b was pushed. Either b removed them itself, or some index removed them that b then removed (directly, or through a chain of pops). Each pop only removes values ≤ the popper’s value. So following the chain, every removed value is ≤ nums[b].

Why popping is safe. Suppose i pops j. Then j < i and nums[j] ≤ nums[i]. Now take any future index k > i, and suppose j would be a valid answer for it, meaning nums[j] > nums[k]. Then nums[i] ≥ nums[j] > nums[k], so i is a valid previous greater for k too. And i is closer to k than j is. So j can never again be the nearest answer for anyone, and removing it loses nothing.

Why the top is the answer. After step 1, the top is > x, because it wasn’t popped. Now look at every index between the top and i. By invariant 2, each one either was just popped (so it’s ≤ x) or sits in the shadow of something that was just popped (so it’s ≤ that, which is ≤ x). So nothing between them is > x, and the top is the nearest index that is.

Why it’s O(n) despite the nested while. Each index is pushed exactly once and popped at most once. So over the whole run, the body of the while loop executes at most n times in total, not n times for each i. On the example there are 6 pushes and 3 pops.

The same loop gives a second answer for free. When i pops j, i is the first index to the right of j with a value ≥ nums[j]. That makes i j’s next greater-or-equal element. In the example, index 3 pops indices 2 and 1, and index 4 pops index 3. So the next greater-or-equal indices are [-1, 3, 3, 4, -1, -1]. Indices 0, 4 and 5 are still on the stack at the end. They were never popped, so they have no next greater-or-equal element.

The four common variants all come from this one loop. I checked each one against a brute-force scan on 2,000 random arrays with duplicates:

You want, for each i Scan Pop while nums[stack[-1]] is Read the answer
previous greater left to right <= x top after popping, for i
previous smaller left to right >= x top after popping, for i
next greater left to right < x at pop time: the popped index’s answer is i
next smaller left to right > x at pop time: the popped index’s answer is i

The “greater” variants keep a decreasing stack. (It’s non-increasing if ties are allowed to stay.) The “smaller” variants keep an increasing one. Whether the pop condition is strict (<) or not (<=) decides how ties behave. The conditions in the table give strictly greater and strictly smaller answers.

Diagram

Previous greater element with a monotonic stack on [5, 3, 1, 3, 4, 2]Stack of index: value after each i. i=0 pushes 0, answer -1. i=1 answer 0. i=2 answer 1. i=3 pops 2 and 1, answer 0, stack [0, 3]. i=4 pops 3, answer 0, stack [0, 4]. i=5 answer 4, stack [0, 4, 5]. Answer [-1, 0, 1, 0, 0, 4], 6 pushes, 3 pops. Green is i, just pushed; amber is the entry under it, which is answer[i]; red dashed entries were popped by i.previous greater element: for each i, the nearest j < i with nums[j] > nums[i]503112334425numsindexentry = index : valuei, just pushedbelow it = answer[i]i = 0, x = 50 : 5answer[0] = -1i = 1, x = 30 : 51 : 3answer[1] = 0i = 2, x = 10 : 51 : 32 : 1answer[2] = 1i = 3, x = 30 : 53 : 31 : 32 : 1poppedanswer[3] = 0i = 4, x = 40 : 54 : 43 : 3poppedanswer[4] = 0i = 5, x = 20 : 54 : 45 : 2answer[5] = 4answer = [-1, 0, 1, 0, 0, 4] · 6 pushes, 3 pops

The i = 3 panel is the one to study. The new 3 hides the 1 at index 2, because 1 ≤ 3. It also hides the older 3 at index 1, because 3 ≤ 3 and we want strictly greater. Then it stops at the 5 at index 0, which becomes the answer. In every panel, the stack values read as a strictly decreasing sequence from bottom to top.

Implementation

def previous_greater(nums: list[int]) -> list[int]:
    """answer[i] = index of the nearest j < i with nums[j] > nums[i], or -1 if none."""
    answer = [-1] * len(nums)  # -1 remains wherever nums[0..i-1] has nothing > nums[i]
    stack = []  # indices, with nums[stack[0]] > nums[stack[1]] > ... > nums[stack[-1]]
    for i, x in enumerate(nums):
        # Pop every index j with nums[j] <= x. Such a j lies left of i and nums[j] <= nums[i],
        # so for any later k with nums[j] > nums[k], nums[i] > nums[k] as well and i is closer.
        # [5, 3, 1, 3, 4, 2] at i = 3 (x = 3): pops index 2 (1 <= 3), then index 1 (3 <= 3),
        # then stops at index 0 because 5 <= 3 is false.
        while stack and nums[stack[-1]] <= x:
            stack.pop()
        if stack:
            # stack[-1] survived the loop, so nums[stack[-1]] > x, and every index strictly
            # between stack[-1] and i holds a value <= x. At i = 3: stack[-1] = 0 (value 5),
            # and indices 1..2 hold 3 and 1, both <= 3. So answer[3] = 0.
            answer[i] = stack[-1]
        # else: an empty stack means no value > x in nums[0..i-1].
        # At i = 0 the stack starts empty, so answer[0] stays -1.
        stack.append(i)  # i may be the previous greater for some later index
    return answer

Here is what it returns for the worked example and some edge cases:

Input Output
[5, 3, 1, 3, 4, 2] [-1, 0, 1, 0, 0, 4]
[] []
[1] [-1]
[1, 2, 3] [-1, -1, -1]
[3, 2, 1] [-1, 0, 1]
[2, 2, 2] [-1, -1, -1]

Complexity, with n = len(nums):

  • O(n) time. There are n pushes and at most n pops across the whole loop.
  • O(n) extra space. A strictly decreasing input like [3, 2, 1] never pops, so the stack ends up holding all n indices.

Recognition

These are the signals:

  • The words nearest, next, previous, or first … to the left/right, combined with bigger, smaller, warmer, taller or shorter.
  • “How far can this element extend before something blocks it?” The blocker is the nearest smaller (or bigger) element on each side.
  • A brute force whose inner loop scans outward and stops at the first element that beats the current one. That early stop is the giveaway.
  • Something that gets blocked or absorbed by what’s ahead of it.

Here is where those signals show up in this topic’s list. Daily Temperatures asks about the next warmer day. Largest Rectangle In Histogram asks how far each bar can extend before it hits a shorter one. Car Fleet has cars that can’t pass the one ahead of them.

When not to use it:

  • You need the max or min over everything to one side, not the nearest element that qualifies. A running max or min is simpler (see the transfer test).
  • You need the max or min of a sliding window. There, old elements also have to leave from the bottom when they fall out of the window. That needs a monotonic deque, covered in Sliding Window.
  • You need the k-th largest, or the min of a set that changes in arbitrary ways. That’s a heap.

Pitfalls

  • Strict versus non-strict. Using <= or < in the pop condition decides what happens with duplicates. On the example, popping only on < gives the previous greater-or-equal instead: [-1, 0, 1, 1, 0, 4]. Index 3 would stop at the earlier 3. Decide which one the problem wants before you write the condition.
  • Pushing values instead of indices. With only values, you can’t compute a distance or a width, and you can’t write into answer[j] at pop time. Push indices and look the values up in nums.
  • if instead of while. One new element can hide many older ones. In the example, index 3 popped two. A single if pops at most one, which breaks the invariant.
  • Leftovers. Indices still on the stack at the end never found their “next” element. Fill answer with a default up front (−1, n, 0, whatever the problem says). Then they’re handled without a second loop.
  • Believing it’s O(n²). A while inside a for looks quadratic. Count pushes and pops instead of looking at how the loops are nested.

Active Recall

1. For nums = [5, 3, 1, 3, 4, 2], what are the stack’s indices and values right after processing i = 4, and which invariant do they show?

2. At i = 3, index 1 (value 3) is popped by the new value 3. Why is it safe to throw index 1 away permanently, for every future index?

3. Change the pop condition from <= x to < x. What does the answer array become for the example, and what does it now mean?

4. With the original <= loop, which indices get popped by index 3 and by index 4? What does being popped tell you about those indices, as opposed to their “previous greater”?

5. Someone says the loop is O(n²) because of the while inside the for. Give the argument that it’s O(n), using the example’s counts.

Answer out loud or on paper first.

Answer these yourself, then get them checked byChatGPT ↗Claude ↗

Mini-task

Skipped for this topic. Largest Rectangle In Histogram makes you work out from scratch what a pop means for the bar being popped. So you’ll practise this technique on your own when you solve it.

Transfer test

For each index of an array, you want the largest value anywhere to its right (or nothing for the last index). For [5, 3, 1, 3, 4, 2] that’s [4, 4, 4, 4, 2, None]. Would you use a monotonic stack? Why?

Decide, then get a second opinion fromChatGPT ↗Claude ↗

Integration

How the two modules make up the topic. Every problem in this list is about items that are still waiting, and the event that resolves them.

  • The plain stack handles the case where the item to resolve is always the most recent one. Think nesting, the latest operands, or the latest action.
  • The monotonic stack handles the case where one new element can resolve many waiting items at once, because it’s bigger or smaller than all of them.

Both do all their work in a single left-to-right pass. Both are O(n) for the same reason: each item is pushed once and popped at most once. And in both, the pop is the moment the answer gets decided.

Choosing between competing approaches.

If the problem needs … Reach for Why not a stack
The most recent pending item, nesting, undo Stack It is a stack
Nearest bigger or smaller element to one side Monotonic stack It is one
The oldest pending item first, level by level Queue (deque) LIFO gives the wrong order
Max or min of a moving window Monotonic deque Old items must also leave from the bottom
Max or min over everything so far Running variable Nothing is ever removed, so no structure is needed
Smallest or largest of a changing set, k-th largest Heap A stack only exposes the newest, not the extreme
A pair in a sorted array Two pointers No pending items at all

A recognition checklist for an unfamiliar problem.

  1. As I scan, does each element leave something pending (still waiting) that a later element will resolve?
  2. Is the thing resolved always the most recent pending item? Then use a plain stack.
  3. Can one new element resolve several pending items at once, because it beats them all on size? Then use a monotonic stack. Decide three things: previous or next, greater or smaller, strict or not.
  4. Do I need to know which items are pending, or only how many? If only how many, a counter may replace the stack.
  5. What goes on the stack: the value, the index, or both? If the answer involves a distance, a width or a position, push the index.
  6. What happens to items still on the stack when the input ends?
  7. Sanity check: can I bound the total number of pops by n? If yes, it’s O(n).

The problems

Work through these with the solving cycle from Part 1. Give each problem a 15-minute struggle, write down one key sentence per problem, then review it with spaced repetition.

While you struggle with a stack problem, ask yourself:

  • What is pending?
  • What event resolves it?
  • Does that event resolve only the newest item, or several at once?

Before you write any code, take a five-element example and draw the stack after each element.

Take this lesson as a live session

If you’d rather be taught this interactively, with the coach waiting for your answers, open the full lesson prompt in a chat.

Open the full lesson inChatGPT ↗Claude ↗