NeetCode 150, stage 4: Stack

← Sliding Window · All 150 problems · Binary Search →

A stack keeps the items that are not complete, with the most recent item on top. In Go a slice is the stack: append pushes, and a new slice expression pops. This stage trains you to see which items must wait, and which event resolves them.

Garden notes: the Go syntax for this stage, Stack-Based pattern, Stacks.

Problems on this page

Templates to memorize

Template A: Matching stack

Signal

The input has items that open and close, and the pairs nest: brackets, tags, directory paths. The most recent opener must close first.

// TEMPLATE A: matching stack. An opener waits on the stack for its closer.
func balanced(s string) bool {
    pairs := map[byte]byte{')': '(', ']': '['} // closer -> its opener
    stack := []byte{}
    for i := 0; i < len(s); i++ {
        open, isCloser := pairs[s[i]]
        if !isCloser {
            stack = append(stack, s[i]) // 1. PUSH an opener
            continue
        }
        // 2. MATCH the top
        if len(stack) == 0 || stack[len(stack)-1] != open {
            return false
        }
        stack = stack[:len(stack)-1] // 3. POP the opener
    }
    return len(stack) == 0 // 4. LEFTOVER openers make the answer false
}

The moves are PUSH, MATCH, POP, then the LEFTOVER test. Test len(stack) == 0 before you read the top. Do the leftover test at the end, because "((" has no wrong closer and is still not valid.

Say it

“The last bracket that I open is the first one that I must close, and that is a stack. I push openers, I match each closer with the top, and the stack must be empty at the end.”

Template B: Paired stack

Signal

A design problem wants push, pop and one more query, such as the minimum, and each operation must be O(1).

// TEMPLATE B: paired stack. best[i] is the answer for the items vals[0..i].
type maxStack struct {
    vals []int // the values
    best []int // best[i]: the maximum of vals[0..i]
}
 
func (s *maxStack) push(x int) {
    top := x
    if len(s.best) > 0 {
        // compare with the answer below
        top = max(top, s.best[len(s.best)-1])
    }
    s.vals = append(s.vals, x) // 1. PUSH BOTH
    s.best = append(s.best, top)
}
 
func (s *maxStack) pop() {
    // 2. POP BOTH: the old answer is on top again
    s.vals = s.vals[:len(s.vals)-1]
    s.best = s.best[:len(s.best)-1]
}
 
// 3. READ THE TOP
func (s *maxStack) max() int { return s.best[len(s.best)-1] }

The moves are PUSH BOTH, POP BOTH, then READ THE TOP. The second stack stores the answer to the query for each height of the first stack. A pop then brings back the answer from before, with no search. Keep the two stacks at the same length.

Say it

“I keep a second stack that stores the minimum at each height. A pop removes one item from each stack, so the minimum from before is on top again, and each operation is O(1).”

Template C: Stack as evaluator

Signal

The input is an expression in postfix notation (Reverse Polish notation). More generally, each token applies to the most recent results.

// TEMPLATE C: the stack as an evaluator of postfix tokens.
// The stack holds the results that wait for an operator.
func evalPostfix(tokens []string) int {
    stack := []int{}
    for _, tok := range tokens {
        if n, err := strconv.Atoi(tok); err == nil {
            stack = append(stack, n) // 1. PUSH a number
            continue
        }
        b := stack[len(stack)-1] // 2. POP TWO: the top is the right operand
        a := stack[len(stack)-2]
        stack = stack[:len(stack)-2]
        res := a + b // 3. APPLY the operator
        if tok == "-" {
            res = a - b
        }
        stack = append(stack, res) // 4. PUSH the result
    }
    return stack[0]
}

The moves are PUSH a number, POP TWO, APPLY, then PUSH the result. The first value that you pop is the right operand. That order changes the result of - and /.

Say it

“Numbers wait on the stack. An operator pops two values, the right operand first, and pushes the result, so it is one pass and O(n).”

Template D: Backtracking with counters

Signal

The problem says “generate all” the valid strings or combinations. The number of results grows exponentially, so the task is to build only the valid ones.

// TEMPLATE D: backtracking with counters. The call stack is the stack.
// It builds each string of n pairs of brackets that is balanced.
func allBalanced(n int) []string {
    res := []string{}
    path := make([]byte, 0, 2*n) // the string that the recursion builds
    var build func(open, closed int)
    build = func(open, closed int) {
        if len(path) == 2*n {
            res = append(res, string(path)) // RECORD a copy of the path
            return
        }
        if open < n { // the counters permit only valid choices
            path = append(path, '(')  // 1. CHOOSE
            build(open+1, closed)     // 2. EXPLORE
            path = path[:len(path)-1] // 3. UNDO
        }
        if closed < open {
            path = append(path, ')')
            build(open, closed+1)
            path = path[:len(path)-1]
        }
    }
    build(0, 0)
    return res
}

The moves are CHOOSE, EXPLORE, then UNDO. Here the call stack is the stack. The two counters stop a bad branch before it starts: open < n permits an opener, and closed < open permits a closer. Record string(path), which is a copy, because the recursion changes path after that.

Say it

“I can open while I have openers left, and I can close only while something is open. So each string that reaches full length is valid, and I never filter.”

Template E: Monotonic stack

Signal

The problem asks, for each item, for the next larger item, the next smaller item, or how far the item can extend. A brute-force answer scans to the right from each index.

// TEMPLATE E: monotonic stack. It holds the indexes that wait for an
// answer.
// Here the answer is the index of the next larger value, or -1.
func nextGreater(nums []int) []int {
    res := make([]int, len(nums))
    for i := range res {
        res[i] = -1 // the default: no larger value comes
    }
    // indexes that wait: their values decrease from the bottom up
    stack := []int{}
    for i, x := range nums {
        // 1. RESOLVE: x is the answer for each smaller value on the top
        for len(stack) > 0 && nums[stack[len(stack)-1]] < x {
            j := stack[len(stack)-1]
            // POP the index that has its answer
            stack = stack[:len(stack)-1]
            res[j] = i
        }
        stack = append(stack, i) // 2. PUSH: index i waits now
    }
    return res
}

The moves are RESOLVE, then PUSH. The stack holds the indexes that wait for an answer. The current item resolves each index on the top that it answers, and then it waits too. The loop pushes each index one time and pops it one time at most, so the total is O(n). Store indexes, not values, because the answer is usually a distance.

Say it

“The stack holds the indexes that still wait for a larger value, and each new value pops the smaller ones and becomes their answer. Each index is pushed and popped once, so it is O(n) although there is a nested loop.”

Mistakes in this stage

  • stack[len(stack)-1] on an empty stack panics. Test len(stack) > 0 first, on the left of &&.
  • stack[:len(stack)-1] alone does not pop. Assign the result: stack = stack[:len(stack)-1].
  • In Go, / on two ints truncates toward zero, and float64(a) / float64(b) keeps the fraction. Convert before you divide.
  • A []byte path in a recursion is shared memory. Append string(path) to the result, not the slice.

Solved with comments

Each problem hides its answer in three steps, so the page works as a test. Read the problem on LeetCode first. Then open the steps in order, and only as far as you need:

  1. Which pattern? Say the pattern and the template aloud. Then open step 1 to check.
  2. The idea. If you are blocked, open step 2. It has the key idea and the complexity, and no code.
  3. The Go solution. Open step 3 last. Then close it and type the solution from memory.

Each solution has the function name and the signature that LeetCode gives you. The code does not show the given types (ListNode, TreeNode, Node) or the imports. LeetCode adds the standard library imports for you. For a local file, each solution lists the imports that it needs.

20. Valid Parentheses

LeetCode 20 · Easy

155. Min Stack

LeetCode 155 · Medium

150. Evaluate Reverse Polish Notation

LeetCode 150 · Medium

22. Generate Parentheses

LeetCode 22 · Medium

739. Daily Temperatures

LeetCode 739 · Medium

853. Car Fleet

LeetCode 853 · Medium

84. Largest Rectangle in Histogram

LeetCode 84 · Hard


← Sliding Window · All 150 problems · Binary Search →