Notes
All notes

Heap / Priority Queue (LeetCode #8)

A heap answers one question cheaply and repeatedly: what is the current extreme? Whenever a problem says “k-th”, “k largest”, “k closest”, “running median”, or “top k”, a heap is usually the intended tool. This post covers the seven NeetCode Heap problems.

The technique

A min-heap keeps its smallest element at the root (index 0). Push and pop are \(O(\log n)\); peek is \(O(1)\); building from an array is \(O(n)\). Python’s heapq is a min-heap; negate values for a max-heap.

import heapq
h = [5, 1, 9]
heapq.heapify(h)          # h[0] is now 1
heapq.heappush(h, 2)
smallest = heapq.heappop(h)

Top-k. For the k largest, keep a min-heap of size k; the root is the k-th largest.

Two heaps. For a running median, keep the lower half in a max-heap and the upper half in a min-heap, balanced to differ by at most one.

Kth Largest Element in a Stream

The question. Design a class that, given k and a stream of numbers, returns the k-th largest element after each add.

k = 3, nums = [4,5,8,2]
add(3)  -> 4
add(5)  -> 5
add(10) -> 5

The idea. Keep a min-heap of exactly the k largest values. When a new number arrives, push it and pop the smallest if the heap exceeds k. The root is the k-th largest.

Walk it through with [4,5,8,2]: heap becomes [4,5,8] (the 3 largest); add(3) → push 3, pop 3 → heap [4,5,8], root 4. add(5) → heap [5,5,8], root 5. add(10) → push 10, pop 5 → [5,8,10], root 5.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  n/.style={draw, thick, circle, minimum size=0.6cm, font=\small\ttfamily, inner sep=0pt},
  a/.style={->, thick}]
  \node[n, fill=orange!25] (r) at (0,0) {4};
  \node[n, fill=blue!8] (l) at (-1.1,-1.0) {5}; \node[n, fill=blue!8] (rr) at (1.1,-1.0) {8};
  \draw[a] (r) -- (l); \draw[a] (r) -- (rr);
  \node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (0,-0.55) {root = kth largest};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-1.55) {keep exactly k; the root is the answer};
\end{tikzpicture}
import heapq

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = nums
        heapq.heapify(self.heap)
        while len(self.heap) > k:
            heapq.heappop(self.heap)
    def add(self, val):
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)
        return self.heap[0]

\(O(n \log k)\) to build, \(O(\log k)\) per add, \(O(k)\) space.

Last Stone Weight

The question. Repeatedly smash the two heaviest stones: if they are equal both vanish; otherwise the smaller vanishes and the larger becomes their difference. Return the last remaining weight, or 0.

Input:  [2,7,4,1,8,1]  -> 1

The idea. We always need the two largest, so use a max-heap. Repeatedly pop two, push their difference if nonzero.

Walk it through on [2,7,4,1,8,1]: 8 and 7 → 1; then 4 and 2 → 2; then 2 and 1 → 1; then 1 and 1 → 0; then 1 remains → 1.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.6cm, minimum height=0.55cm, font=\small\ttfamily}]
  \node[c, fill=blue!8] at (0,0.9) {8}; \node[c, fill=blue!8] at (0.66,0.9) {7};
  \draw[->, thick] (0.33,0.6) -- (0.33,0.15);
  \node[c, fill=green!15] at (0.33,-0.15) {1};
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.33,-0.7) {smash the two heaviest; the rest survives};
\end{tikzpicture}
import heapq

def last_stone_weight(stones):
    heap = [-s for s in stones]        # max-heap via negatives
    heapq.heapify(heap)
    while len(heap) > 1:
        a = -heapq.heappop(heap)       # largest
        b = -heapq.heappop(heap)       # second largest
        if a != b:
            heapq.heappush(heap, -(a - b))
    return -heap[0] if heap else 0

\(O(n \log n)\) time, \(O(n)\) space.

K Closest Points to Origin

The question. Return the k points closest to the origin.

Input:  [[1,3],[-2,2]], k = 1  ->  [[-2,2]]

The idea. “K closest” is “k smallest by distance”, so keep a max-heap of size k keyed by distance and evict the farthest. Store -distance since Python has only a min-heap. Compare squared distances to avoid square roots.

def k_closest(points, k):
    heap = []
    for x, y in points:
        d = x * x + y * y
        heapq.heappush(heap, (-d, x, y))
        if len(heap) > k:
            heapq.heappop(heap)         # remove the farthest
    return [[x, y] for _, x, y in heap]

\(O(n \log k)\) time, \(O(k)\) space.

Kth Largest Element in an Array

The question. Return the k-th largest value in an array.

The idea. A size-k min-heap in one pass, or quickselect (average \(O(n)\)) for a static array.

def find_kth_largest(nums, k):
    heap = nums[:k]
    heapq.heapify(heap)
    for x in nums[k:]:
        if x > heap[0]:
            heapq.heapreplace(heap, x)
    return heap[0]

\(O(n \log k)\) time, \(O(k)\) space.

Task Scheduler

The question. Given tasks and a cooldown n, find the minimum time units to finish all tasks (including idle slots).

Input:  tasks = ["A","A","A","B","B","B"], n = 2  -> 8      (A B _ A B _ A B)

The idea. The most frequent task, appearing f times, forces f blocks of length n+1. Use the closed form, taking the max with the total number of tasks:

\[ \text{time} = \max\Big((f-1)(n+1) + (\#\text{tasks with frequency } f),\ \ \#\text{tasks}\Big) \]

Walk it through. f = 3 (A and B), two tasks tie at 3, total 6. (3-1)(2+1) + 2 = 8; max with 6 → 8.

from collections import Counter

def least_interval(tasks, n):
    counts = Counter(tasks)
    f = max(counts.values())
    ties = sum(1 for c in counts.values() if c == f)
    return max(len(tasks), (f - 1) * (n + 1) + ties)

\(O(n)\) time.

Design Twitter

The question. Design a simplified Twitter: postTweet, getNewsFeed (10 most recent tweets from you and your followees), follow, unfollow.

postTweet(1, 5); getNewsFeed(1) -> [5]
follow(1, 2); postTweet(2, 6); getNewsFeed(1) -> [6, 5]

The idea. Store each user’s tweets with a global (or per-user) timestamp. For the feed, gather the heads of every relevant user’s tweet list into a max-heap keyed by recency, pop up to 10, and push each popped tweet’s next-older neighbour — the same k-way merge as Merge K Sorted Lists.

Walk it through. User 1 follows 1 and 2. Tweets: 1→[(5,t1)], 2→[(6,t2)]. Heap of the newest from each: (t2,6), (t1,5). Pop (t2,6); its list is exhausted. Pop (t1,5). Feed [6,5].

import heapq
from collections import defaultdict

class Twitter:
    def __init__(self):
        self.time = 0
        self.tweets = defaultdict(list)       # user -> [(time, tweetId)]
        self.following = defaultdict(set)     # user -> set of followees
    def postTweet(self, userId, tweetId):
        self.time += 1
        self.tweets[userId].append((self.time, tweetId))
    def getNewsFeed(self, userId):
        users = self.following[userId] | {userId}
        heap = []
        for u in users:
            if self.tweets[u]:
                idx = len(self.tweets[u]) - 1
                t, tid = self.tweets[u][idx]
                heapq.heappush(heap, (-t, tid, u, idx))
        feed = []
        while heap and len(feed) < 10:
            negt, tid, u, idx = heapq.heappop(heap)
            feed.append(tid)
            if idx > 0:
                t, tid2 = self.tweets[u][idx - 1]
                heapq.heappush(heap, (-t, tid2, u, idx - 1))
        return feed
    def follow(self, followerId, followeeId):
        self.following[followerId].add(followeeId)
    def unfollow(self, followerId, followeeId):
        self.following[followerId].discard(followeeId)

\(O(10 \log U)\) per feed (U = followees), \(O(1)\) for the others.

Find Median from Data Stream

The question. Design add(x) and median().

add(1); add(2); median() -> 1.5; add(3); median() -> 2

The idea. Keep the lower half in a max-heap low and the upper half in a min-heap high, balanced so their sizes differ by at most one. The median is at the roots (average them if even).

Walk it through adding 1,2,3: after 1 low=[1]; after 2 low=[1], high=[2], median 1.5; after 3 low=[1,2] (max-heap), high=[3], median 2.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.7cm, minimum height=0.55cm, font=\small\ttfamily}]
  \node[c, fill=blue!10] at (0,0) {2}; \node[c, fill=blue!10] at (-0.76,0) {1};
  \node[c, fill=orange!15] at (1.6,0) {3};
  \node[font=\scriptsize\ttfamily, anchor=north] at (-0.38,-0.35) {low (max)};
  \node[font=\scriptsize\ttfamily, anchor=north] at (1.6,-0.35) {high (min)};
  \draw[very thick, green!55!black] (0.55,-0.3) -- (0.55,0.3);
  \node[font=\scriptsize\ttfamily, text=green!45!black, anchor=north] at (0.55,-0.7) {balanced halves};
\end{tikzpicture}
class MedianFinder:
    def __init__(self):
        self.low, self.high = [], []     # low: max-heap (negated)
    def add(self, x):
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))   # move max to high
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))
    def median(self):
        if len(self.low) > len(self.high):
            return -self.low[0]
        return (-self.low[0] + self.high[0]) / 2

\(O(\log n)\) add, \(O(1)\) median.

Pitfalls

QQuestionSelf-check

Why does a size-\(k\) min-heap yield the \(k\) largest? How do two heaps give an \(O(1)\) median?

ASolution

The heap keeps the k largest seen so far and evicts the smallest when it exceeds k. Two heaps split the stream into lower and upper halves with the median between their roots, so it is read in \(O(1)\) while insertion is \(O(\log n)\).

Next: Backtracking (LeetCode #9) — explore, prune, and undo.