Kth Largest Element in a Stream
After each new number in a stream, return the kth largest so far, keeping only k numbers in a min-heap.
Design a class that keeps answering one question about a growing stream of numbers: which number is the kth largest so far? The class has two parts:
creates the object withKthLargestInStream(int k, int[] nums) and the numbers the stream starts with.k addsadd(int val) to the stream and returns the kth largest of all the numbers so far, that is, the kth one when counting down from the largest.val
Equal numbers count separately, so in 5, 5, 8 the second largest is 5. Whenever addk
Example 1
Output: 4, 5, 5, 8, 8
Example 2
Output: -1, 0, 0
The Idea
Think of a game's high-score table that shows only the top three. New scores keep arriving, and after each one you want the score in third place. Example 1 is exactly that, with k = 3. The stream starts with 4, 5, 8 and 2. The three largest are 8, 5 and 4, so third place is 4.
Then add(3)add(5)
The stream keeps growing with every call. Does the object have to remember every number in it?
It does not. Numbers are only ever added, never taken away, so third place can stay the same or move up, but never down. Once a number has dropped out of the top three, like 2 at the start, it can never get back in. So the object only needs the three largest numbers so far, and the answer is the smallest of those three.
Look at the picture above. Each row is one call, and the column "the 3 largest so far" is all the object keeps. When a fourth number arrives, the smallest of the four moves to the "dropped" column. The orange box, the smallest number kept, is the "3rd largest" that add
In the row add(10)add(4)
So every call needs the same two moves: find the smallest of the kept numbers, and drop it when a fourth number arrives. Whatever holds the kept numbers has to make both of them cheap.
Solution Approach
The code needs three decisions: which numbers to keep, how to reach the smallest kept number quickly, and what the constructor does with the starting numbers. The simple way, which keeps every number, shows why the first decision matters.
Keeping every number
Why not store the whole stream in a list and sort it after each add
Keeping only the k largest
As the picture showed, a number that falls below the kth largest never matters again. So the object holds at most k numbers. Each new number goes in, and if that makes k + 1, the smallest of them goes out. Until the stream has k numbers, nothing is dropped.
Reaching the smallest kept number
Which structure hands back the smallest number quickly and accepts new ones cheaply? A min-heap does. It keeps its numbers in a loose order: not fully sorted, but always with the smallest one at the top. In Example 1, a min-heap holding 4, 5 and 8 has 4 on top.
Reading the top takes one step. Adding a number, or removing the top, takes about log k steps. The heap stores its numbers in levels that double in size, about log k of them, and a change moves one number up or down through those levels.
In Java, a min-heap is the class PriorityQueuejava.utilofferpeekpollComparator.naturalOrder()
The starting numbers
What should the constructor do with numsadd
Java Solution
The class has three parts, plus the number k
: thetopK , a min-heap of the k largest numbers so far, built withPriorityQueue so the smallest is on top.Comparator.naturalOrder() : offersadd(val) toval , polls the top iftopK now holds k + 1 numbers, and returnstopK , the kth largest.peek()- The constructor: stores
and passes each starting number tok .add
The mainrunadd
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
public class KthLargestInStream {
private final int k;
// min-heap: the smallest value is always at the top
private final PriorityQueue<Integer> topK = new PriorityQueue<>(Comparator.naturalOrder());
public KthLargestInStream(int k, int[] nums) {
this.k = k;
for (int x : nums) {
add(x); // the starting numbers go through the same rule
}
}
public int add(int val) {
topK.offer(val);
if (topK.size() > k) {
topK.poll(); // drop the smallest: it is no longer among the k largest
}
return topK.peek(); // the smallest of the k largest is the kth largest
}
static void run(int k, int[] nums, int... adds) {
KthLargestInStream stream = new KthLargestInStream(k, nums);
List<Integer> answers = new ArrayList<>();
for (int val : adds) {
answers.add(stream.add(val));
}
System.out.println("k = " + k + ", start " + Arrays.toString(nums)
+ ", add " + Arrays.toString(adds) + " -> " + answers);
}
public static void main(String[] args) {
run(3, new int[] {4, 5, 8, 2}, 3, 5, 10, 9, 4); // Example 1
run(2, new int[] {0}, -1, 3, -5); // fewer than k at the start
run(1, new int[] {}, -3, -2, -4); // k = 1: the largest so far
run(2, new int[] {7, 7, 7}, 7, 1); // all equal
}
}
Running it prints:
k = 3, start [4, 5, 8, 2], add [3, 5, 10, 9, 4] -> [4, 5, 5, 8, 8]
k = 2, start [0], add [-1, 3, -5] -> [-1, 0, 0]
k = 1, start [], add [-3, -2, -4] -> [-3, -2, -2]
k = 2, start [7, 7, 7], add [7, 1] -> [7, 7]
The answers 4, 5, 5, 8, 8 on the first line are the last column of the picture. On the second line, Example 2 starts with only 0, one number fewer than k = 2. After add(-1)
With k = 1, the heap holds a single number, the largest so far: -3, then -2, and -4 does not replace it. On the last line, the 7s count separately, so the second largest is still 7, and 1 never gets in.
Why must the heap be a min-heap? Creating topKComparator.reverseOrder()poll[4, 4, 4, 4, 4]add(3)
Complexity
Each add
- Time: O(log k) per
, becauseadd andoffer each move a number along one path of a heap with at most k + 1 numbers, andpoll reads the top in one step. The constructor costs O(n log k) for n starting numbers, because it callspeek once for each of them.add - Space: O(k), because a number is dropped in the same call that pushes it out of the k largest, however long the stream runs.
The one-off version, on a fixed array, is