Index

Free, with Google

Keep going, free.

A free account opens lessons 2 and 3 of every track, 33 more lessons, and keeps your progress and review cards on every device.

Start free with Google

A chalk plan

Open everything on chalk.

Every lesson, board, video, lab and paper, and the full review decks. Yearly is $39/year.

See plansStart free instead

Kth Largest Element in a Stream

EasyLeetCode 703 ↗

The problem, in one line. Numbers arrive one at a time, and after each arrival you must report the kth largest number seen so far. LeetCode 703.

The tell. A rank, asked again after every new value. “kth largest” with a stream means you never get to see the whole list at once, so you keep only what could still matter.

The wrong first idea

Keep every number in a list, sort it on each arrival, and read the kth from the end.

It is correct. Each add re-sorts a list that keeps growing, so the cost of one add grows with everything ever seen. Most of that list can never be the answer again: a number that is not among the k biggest never will be, because the k biggest only improve.

The invariant

Keep a small pile with k seats, holding the k biggest numbers so far, with the weakest of them on top. The weakest of the k biggest is exactly the kth biggest.

k = 3, seen 4 5 8 2     pile 4 5 8
add 3                   3 is weaker than all, pile stays 4 5 8, answer 4
add 10                  10 enters, 5 is pushed out, pile 5 8 10, answer 5

The sentence that stays true every step: the heap holds the k largest values seen so far, and its top is the kth largest. That is a min-heap, even though the question says largest.

The solution

import heapq

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.heap = []                       # the k biggest so far, weakest on top
        for x in nums:
            self.add(x)

    def add(self, val):
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
            heapq.heappop(self.heap)         # the weakest seat is lost
        return self.heap[0]

kl = KthLargest(3, [4, 5, 8, 2])
print(kl.add(3), kl.add(5), kl.add(10), kl.add(9), kl.add(4))
k1 = KthLargest(1, [])
print(k1.add(-3), k1.add(-9), k1.add(7))
4 5 5 8 8
-3 -3 7
type KthLargest struct {
	k int
	h *minHeap // the k biggest so far, weakest on top
}

func Constructor(k int, nums []int) KthLargest {
	kl := KthLargest{k, &minHeap{}}
	for _, x := range nums {
		kl.Add(x)
	}
	return kl
}

func (kl *KthLargest) Add(val int) int {
	heap.Push(kl.h, val)
	if kl.h.Len() > kl.k {
		heap.Pop(kl.h) // the weakest seat is lost
	}
	return (*kl.h)[0]
}

This uses the same minHeap type as the card before it, with Less returning h[i] < h[j], and imports container/heap. Same calls print 4 5 5 8 8 and -3 -3 7.

Complexity

  • Time O(log k) per add, and the constructor is O(n log k).
  • Space O(k): the heap never holds more than k numbers.

Traps

  • Evicting before inserting. With pile 4 5 8 and an arriving 3, popping first drops the real 4 and the answer becomes 3 instead of 4.
  • Using a max-heap. The top is then the biggest, not the kth, and evicting it throws away the best number.
  • Removing duplicates. With k of 3 and the numbers 5, 5, 5 the answer is 5, and a set would leave nothing to answer with.

Next in the ladder

Kth Largest Element in an Array asks the same rank on a whole array at once, so a heap is one option and sorting or quickselect are the others.