Kth Largest Element in a Stream

EasyHeapLeetCode 703 ↗World 9-17
0:00 / 0:00

Track the kth largest number as new ones stream in. Keep only the top k in a min-heap, and its smallest member is always the answer.

▼

The problem

LeetCode 703 (Easy). Design a class KthLargest(k, nums) whose add(val) appends val to the stream and returns the k-th largest element so far.

Example: KthLargest(3, [4, 5, 8, 2]), then add(3), add(5), add(10), add(9), add(4) → 4, 5, 5, 8, 8.

TRY IT ON LEETCODE ▶

The solution

import heapq

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = []
        for x in nums:
            self.add(x)

    def add(self, val):
        if len(self.heap) < self.k:
            heapq.heappush(self.heap, val)
        else:
            heapq.heappushpop(self.heap, val)
        return self.heap[0]

Transcript

K-th Largest Element in a Stream. Numbers arrive one at a time. Design a class that takes k and some starting numbers, and after each new number is added, returns the k-th largest so far.

Say k is three, and we start with four, five, eight and two. Add three: from the top, that's eight, five, four, so the answer is four. Add five: five. Then ten gives five, nine gives eight, and four still gives eight.

The simple way keeps every number sorted and counts down k from the top. But each new number shifts everything smaller to make room, and the list keeps growing: order n per add.

Here's the key. A number below the top k can never be the answer again, because numbers only join. So keep just k of them, in a min-heap: a club with three seats. The smallest sits in the top seat, by the door, and that's the answer.

A bouncer guards the door. He compares each newcomer with the guest in the top seat. Bigger? The top guest is out, and the newcomer sits down, then sinks to its place. Not bigger? Turned away, and the answer stays.

In code, the constructor just adds each starting number. Add pushes while the heap has room. Once it's full, heap push pop pushes the newcomer and pops the smallest: the old top, or the newcomer, straight back out. Then return the top.

Back to the example. Four, five and eight take the seats, and two is turned away. Three is turned away too: four. Five bounces four: five. Ten bounces a five: still five. Nine bounces the other five: eight. And four is turned away: eight.

Each add is one check at the door, and at most one trip down a heap only log k levels deep: order log k time. And the club never grows past k seats: order k space.

Keep the top k, seat the smallest by the door, and read it off the top. That's K-th Largest Element in a Stream.