Kth Largest Element in a Stream
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Build a class that is given k and starting numbers, and whose add(val) inserts a number and returns the current k-th largest.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1What do you have to store between calls? Not all numbers.
- Hint 2The k largest numbers, with the smallest of them easy to reach.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
The talent-show podium that stays open all season. Contestants arrive one at a time. After each arrival, the announcer states who stands at the edge of the top-k podium. Nobody needs the whole ranking of all past contestants, just the podium.
- The obvious way
Keep every number, sort on each add: O(n log n) per call.
- The key insight
Keep a min-heap of at most k numbers. In add: push the value, pop the smallest if there are more than k, and return the top. Each call is O(log k).
- The algorithm
- Constructor: keep k, push all starting numbers while trimming to k.
- add: push the value.
- If more than k numbers, pop the smallest.
- Return the heap top.
Watch it run
Examplek = 3, start = [4, 5, 8, 2]; then add 3, 5, 10, 9, 4
Start: push 4, 5, 8, 2; keep only the 3 largest: {4, 5, 8}. The edge is 4.
podium: 4, 5, 8
Where people slip
- The constructor may get fewer than k numbers; add() is only guaranteed to have a k-th once enough arrived.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
import heapq
class KthLargest:
def __init__(self, k, nums):
self.k = k
self.podium = [] # min-heap of the k largest so far
for number in nums:
self.add(number)
def add(self, val):
heapq.heappush(self.podium, val)
if len(self.podium) > self.k:
heapq.heappop(self.podium) # the weakest steps down
return self.podium[0] # the edge of the podiumNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.