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:

Equal numbers count separately, so in 5, 5, 8 the second largest is 5. Whenever add returns, the stream holds at least k numbers.

Example 1
Input: k = 3, nums = [4, 5, 8, 2], then add(3), add(5), add(10), add(9), add(4)
Output: 4, 5, 5, 8, 8
Example 2
Input: k = 2, nums = [0], then add(-1), add(3), add(-5)
Output: -1, 0, 0
Solution

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) arrives. 3 is lower than 4, so it does not reach the top three, and the answer stays 4. Next comes add(5). The numbers are now 2, 3, 4, 5, 5 and 8, and counting down from the largest, 8, 5, 5, the third is 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.

Example 1 with k = 3. Each row is one call. The column 'the 3 largest so far' holds the kept numbers, the smallest of four goes to the 'dropped' column, and the smallest kept number is the 3rd largest: 4, 5, 5, 8, 8.

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 returns.

In the row add(10), 10 pushes out one 5, but the other 5 is still kept, so the answer stays 5. In the last row, add(4), the new 4 is itself the smallest of four, so it is dropped straight away and nothing changes.

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? Sorting n numbers takes about n log n steps, and that cost comes back on every call. Inserting each new number into its sorted place is quicker, but it can still shift all n numbers. Either way the list grows with the stream, although only k of its numbers can ever be the answer again.

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 PriorityQueue from java.util. Its offer adds a number, peek reads the top, and poll removes the top. It orders its numbers smallest first unless told otherwise. The code passes Comparator.naturalOrder(), the comparator for that same smallest-first order, so the choice is visible.

The starting numbers

What should the constructor do with nums? It can hand each starting number to add, as if it had arrived in the stream, and ignore the answers. Then the keep-at-most-k rule lives in one place. In Example 1, this keeps 4, 5 and 8 and drops 2, which is the first row of the picture.

Java Solution

The class has three parts, plus the number k it stores:

  • topK: the PriorityQueue, a min-heap of the k largest numbers so far, built with Comparator.naturalOrder() so the smallest is on top.
  • add(val): offers val to topK, polls the top if topK now holds k + 1 numbers, and returns peek(), the kth largest.
  • The constructor: stores k and passes each starting number to add.

The main method uses a small helper, run, that builds one object, calls add for each value and prints the answers. It runs both examples, k = 1 with no starting numbers, and a stream where every number but the last is 7.

Java
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:

Output
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) the heap holds 0 and -1, and the smaller, -1, is the answer. Then 3 pushes -1 out, the answer becomes 0, and -5 is dropped as soon as it arrives.

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 topK with Comparator.reverseOrder() instead makes it a max-heap, with the largest number on top. Then poll drops the largest, and the object keeps the k smallest numbers. With that one change, the Example 1 line ends in [4, 4, 4, 4, 4]. Each answer is the third smallest number, and after add(3) the three smallest stay 2, 3 and 4.

Complexity

Each add works only on the heap, which never holds more than k + 1 numbers, so the cost depends on k and not on how long the stream has run.

  • Time: O(log k) per add, because offer and poll each move a number along one path of a heap with at most k + 1 numbers, and peek reads the top in one step. The constructor costs O(n log k) for n starting numbers, because it calls add once for each of them.
  • 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 Kth Largest Element in an Array.