DDSA
  • Missions
  • Atlas
  • Lens
  • Lab
←
Atlas · Linear foundations · Topic 4 of 18

Stack

Last in, first out: keep what's still open on a stack and close it when its match arrives.

Spot it

Signals in the question

⌕Things open and close in nested order (brackets, tags, function calls).

⌕You need the most recent unresolved item.

⌕"Next greater / smaller element" or undo behaviour.

The idea

O(n) time · O(n) space

Push each opening item. When a closing item arrives it must match the top of the stack, the most recent open one. If the stack is empty at the end, everything was closed in order.

Template · Match the top

1def is_valid(s):2    pairs = {')': '(', ']': '[', '}': '{'}3    stack = []4    for ch in s:5        if ch in pairs:6            if not stack or stack.pop() != pairs[ch]:7                return False8        else:9            stack.append(ch)10    return not stack

The template, filled in for Valid Parentheses. The highlighted lines are the part every problem of this kind shares.

The best, free

One of each
▶︎WatchStack, explainedNeetCode · YouTube · free↗¶ReadStack data structureGeeksforGeeks · free↗

Practice set

Loading your mission…

Common mistakes

1Popping from an empty stack on a closing bracket that has no partner.

2Forgetting that leftover open items at the end mean invalid.

3Checking only that counts match: "([)]" has equal counts but the wrong order.

Check yourself

Question 1 of 2

Why a stack and not a queue for brackets?