NeetCode 150, stage 9: Heap and Priority Queue

← Tries · All 150 problems · Backtracking →

A heap gives the smallest or the largest item in O(log n), and it does not sort the other items. This stage trains the questions that say “top K”, “Kth” or “next smallest”, and the streams where values arrive one at a time. Go has no priority queue type, so you also learn the five methods that container/heap needs.

Garden notes: the Go syntax for this stage, Top-K Elements pattern.

Problems on this page

Templates to memorize

Template A: The five heap methods

Signal

You need the smallest item again and again while new items arrive. A sort after each change is too slow.

// TEMPLATE A: the five methods that container/heap needs. This type is a
// min-heap of int.
type minHeap []int
 
func (h minHeap) Len() int { return len(h) }
 
// the item that is "less" is on top
func (h minHeap) Less(i, j int) bool { return h[i] < h[j] }
func (h minHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
 
// Push and Pop change the length of the slice, so they need a pointer
// receiver.
func (h *minHeap) Push(x any) { *h = append(*h, x.(int)) } // add at the END
func (h *minHeap) Pop() any { // remove from the END
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[:n-1]
    return x
}
 
// Call the functions heap.Init, heap.Push and heap.Pop. Do not call h.Push
// and h.Pop.
func sortedWithHeap(nums []int) []int {
    // a copy of nums, converted to the heap type
    h := minHeap(slices.Clone(nums))
    heap.Init(&h) // BUILD the heap in O(n)
    res := make([]int, 0, len(nums))
    for len(h) > 0 { // h[0] is the top: PEEK is O(1)
        // POP the smallest in O(log n)
        res = append(res, heap.Pop(&h).(int))
    }
    return res
}

The moves are BUILD or PUSH, PEEK at h[0], then POP. Len, Less and Swap have a value receiver. Push and Pop have a pointer receiver, because they change the length. Your Pop removes the last item, not the first one: heap.Pop moves the top to the end before it calls your method.

Say it

“Go has no built-in priority queue, so I implement heap.Interface with five methods. Push and pop are O(log n), and the top is O(1).”

Template B: Heap of size K

Signal

The problem asks for the K largest, the K closest or the Kth item. K is much smaller than n, or the values come from a stream.

// TEMPLATE B: a heap of size k. For the k LARGEST values, use a MIN-heap.
func kLargest(nums []int, k int) []int {
    h := minHeap{}
    for _, x := range nums {
        heap.Push(&h, x) // 1. PUSH each value
        if len(h) > k {
            // 2. TRIM: remove the smallest, it is not in the top k
            heap.Pop(&h)
        }
    }
    return h // 3. the k largest values. h[0] is the kth largest
}

The moves are PUSH, then TRIM when the heap has more than k items. The heap type is the opposite of the question. For the K largest values, use a min-heap, so the trim removes the smallest one. For the K smallest values, use a max-heap.

Say it

“I keep a min-heap of size k. Each value costs O(log k), so the total is O(n log k) time and O(k) space.”

Template C: Max-heap by a different Less

Signal

Each step takes the largest item, changes it and puts a result back. The problem is a simulation.

// TEMPLATE C: a max-heap. Only Less changes: > in place of <.
type maxHeap []int
 
func (h maxHeap) Len() int { return len(h) }
 
// the largest value is on top
func (h maxHeap) Less(i, j int) bool { return h[i] > h[j] }
func (h maxHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *maxHeap) Push(x any)        { *h = append(*h, x.(int)) }
func (h *maxHeap) Pop() any {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[:n-1]
    return x
}
 
// Simulation: take the two largest values, put one new value back.
func combineLargest(h *maxHeap) {
    a := heap.Pop(h).(int) // POP the largest
    b := heap.Pop(h).(int) // POP the second largest
    heap.Push(h, a-b)      // PUSH the result
}

The moves are POP the largest items, then PUSH the result. Only Less is different from Template A. For a heap of points or structs, Less compares one property of the two items. Do not negate the values to get a max-heap when a correct Less does the same.

Say it

“A max-heap in Go is the same five methods with the comparison in Less turned around.”

Template D: Two heaps for the median

Signal

You must give the median, or the middle items, of a stream after each new value.

// TEMPLATE D: two heaps cut a stream in the middle.
type halves struct {
    // the smaller half: its top is the largest value of this half
    small maxHeap
    // the larger half: its top is the smallest value of this half
    large minHeap
}
 
func (s *halves) add(x int) {
    heap.Push(&s.small, x) // 1. ADD to small
    // 2. MOVE the top of small to large
    heap.Push(&s.large, heap.Pop(&s.small))
    // 3. BALANCE: small has the same size or one more
    if len(s.large) > len(s.small) {
        heap.Push(&s.small, heap.Pop(&s.large))
    }
}
 
func (s *halves) median() float64 {
    if len(s.small) > len(s.large) {
        return float64(s.small[0]) // odd count
    }
    return float64(s.small[0]+s.large[0]) / 2 // even count
}

The moves are ADD, MOVE, then BALANCE. The move through small makes sure that each value in small is less than or equal to each value in large. The balance keeps the two sizes equal, or gives small one more. Then the median is always at the tops.

Say it

“A max-heap holds the smaller half and a min-heap holds the larger half. An insert is O(log n) and the median is O(1) from the two tops.”

Template E: Max-heap plus cooldown queue

Signal

You schedule tasks, and the same type of task must wait some time before it runs again. The problem asks for the least total time.

// TEMPLATE E: greedy with a max-heap and a cooldown queue.
// counts[i] is the number of tasks of type i (1 or more). A type waits gap
// units between runs.
func timeToRunAll(counts []int, gap int) int {
    h := maxHeap(slices.Clone(counts))
    heap.Init(&h)
    type waiting struct{ left, readyAt int }
    // the types that cool down, in the order they become ready
    queue := []waiting{}
    now := 0
    for len(h) > 0 || len(queue) > 0 {
        if len(h) == 0 {
            // IDLE: jump to the end of the first wait
            now = queue[0].readyAt
        } else {
            now++
            // 1. RUN the type with the most tasks left
            left := heap.Pop(&h).(int) - 1
            if left > 0 {
                // 2. COOL DOWN
                queue = append(queue, waiting{left, now + gap})
            }
        }
        if len(queue) > 0 && queue[0].readyAt == now {
            heap.Push(&h, queue[0].left) // 3. RELEASE back into the heap
            queue = queue[1:]
        }
    }
    return now
}

The moves are RUN, COOL DOWN, then RELEASE. The heap gives the type with the most tasks left, because that type is the one that causes idle time. The queue holds the types that wait. The queue is already in time order, so it does not need a heap.

Say it

“I always run the most frequent task that is ready. A max-heap gives that task, and a queue holds the tasks in cooldown until they can go back.”

Template F: K-way merge with a heap

Signal

You have K sorted lists, and you want the items of all the lists in order. Frequently you need only the first few items.

// TEMPLATE F: merge K sorted lists. The heap holds one cursor for each
// list.
type cursor struct{ value, list, index int }
 
type cursorHeap []cursor
 
// Len, Swap, Push and Pop are the same as in Template A, with cursor in
// place of int.
func (h cursorHeap) Less(i, j int) bool { return h[i].value < h[j].value }
 
func mergeSorted(lists [][]int) []int {
    h := cursorHeap{}
    for i, l := range lists {
        if len(l) > 0 {
            // 1. START: the first item of each list
            h = append(h, cursor{l[0], i, 0})
        }
    }
    heap.Init(&h)
    res := []int{}
    for len(h) > 0 {
        // 2. POP the smallest item of all the lists
        top := heap.Pop(&h).(cursor)
        res = append(res, top.value)
        // 3. ADVANCE in the same list
        if next := top.index + 1; next < len(lists[top.list]) {
            heap.Push(&h, cursor{lists[top.list][next], top.list, next})
        }
    }
    return res
}

The moves are START with the first item of each list, POP the best item, then ADVANCE in the list that it came from. The heap never holds more than K items. Each heap item must know its list and its index, or you cannot advance.

Say it

“The heap holds one item from each list. I pop the smallest and push the next item from the same list, so each step is O(log K).”

Mistakes in this stage

  • h.Push(x) calls your method, and it only appends. Call heap.Push(&h, x) to keep the heap order.
  • heap.Pop returns any. Add a type assertion, as in heap.Pop(&h).(int).
  • A slice that you fill with append is not a heap. Call heap.Init before the first pop.
  • A read of h[0] on an empty heap panics. Test len(h) > 0 before you peek.

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.

703. Kth Largest Element in a Stream

LeetCode 703 · Easy

1046. Last Stone Weight

LeetCode 1046 · Easy

973. K Closest Points to Origin

LeetCode 973 · Medium

215. Kth Largest Element in an Array

LeetCode 215 · Medium

621. Task Scheduler

LeetCode 621 · Medium

355. Design Twitter

LeetCode 355 · Medium

295. Find Median from Data Stream

LeetCode 295 · Hard


← Tries · All 150 problems · Backtracking →