Scrivio Interview library
Heaps and top kStacks, queues and heapsReported 21 times · 14 min read · updated 14 November 2026

Keep track of the median of a stream of numbers as each new number arrives.

1What a running median asks, seen as a school photograph

Think of children lining up for a school photograph, arranged by height from shortest to tallest. The photographer wants the child in the very middle of the line. Now children keep arriving one at a time, and after each arrival the photographer asks again who is in the middle. We could re-line the whole class every time, but that feels like a lot of shuffling for one question. This is exactly our problem, with numbers in place of children.

Let us fix the words. The median of some numbers is the middle one once they are sorted. With an odd count it is the single middle number; with an even count there are two middle numbers, and the median is their average. A stream means the numbers arrive one by one, and a running median means we must report the median after every arrival.

Let us do the example by hand, with the stream 5, 15, 1, 3, 8. After 5, the only number is 5, so the median is 5. After 15 we have 5, 15, two numbers, so the median is (5 + 15) / 2 = 10. After 1 we have 1, 5, 15, and the middle is 5. After 3 we have 1, 3, 5, 15, so we average 3 and 5 and get 4. After 8 we have 1, 3, 5, 8, 15, and the middle is 5. The answers are 5, 10, 5, 4, 5.

PictureThe stream and the median after each arrival

The five numbers in the order they arrive, with the median after each one.

  1. 50151123384
    medians
    5, 10, 5, 4, 5
    after 8
    1 3 [5] 8 15

    1The numbers arrive as 5, 15, 1, 3, 8. Sorting what we have after each arrival gives medians 5, 10, 5, 4 and 5.

What to assume

How many numbers, and how often is the median asked for?
We assume many numbers and a question after every arrival, so both must be fast.
Can numbers repeat or be negative?
Yes.
What do we return for an even count?
The average, as a double.
What if nobody has arrived yet?
We throw an exception.
Can a value be as large as Integer.MAX_VALUE?
Yes, so adding two middle values must not overflow.

Here is the comforting part. Look back at what we used each time: only the one or two numbers in the middle. The order of 1 and 3, far from the middle, never mattered. So the problem is smaller than it looks; we do not need to keep everything sorted, only to keep a good grip on the middle.

A careful candidate asks a few questions first. How many numbers, and how often is the median asked for? We assume many numbers and a question after every arrival, so both must be fast. Can numbers repeat or be negative? Yes. What do we return for an even count? The average, as a double. What if nobody has arrived yet? We throw an exception. Can a value be as large as Integer.MAX_VALUE? Yes, so adding two middle values must not overflow.

2How to recognise the heaps pattern

A beginner reading this question usually thinks of sorting, because the median is defined on sorted numbers. That is a natural thought, and it leads to the brute force we will try next. But the photograph has already hinted that sorting is more than we need. Let us read the question for clues.

The first clue is the word stream. Numbers keep arriving and we must answer after each one, so whatever we keep must be cheap to add to. A method that does a lot of work once and then answers many questions will not help, because the numbers keep changing.

The second clue is the word median itself. We need only the middle, not the whole order. Here is the step that unlocks everything. The middle of the line is the tallest child of the shorter half, and at the same time the shortest child of the taller half. So if we split the children into two groups at the middle, the median is always found at the very front of one group or the other, right next to the dividing line.

That points to the heaps and top k family. A heap is a structure that always keeps its largest item on top, a max-heap, or its smallest item on top, a min-heap, and lets us add an item or remove the top quickly. The general rule is that when a problem keeps asking for the largest, the smallest, or the item next to a boundary in a collection that keeps changing, a heap is the first tool to try. Here we use two: a max-heap for the shorter half, so its tallest is on top, and a min-heap for the taller half, so its shortest is on top.

Some tools look similar but fall short. A sorted array gives the median by index, but every new number must be squeezed into place, shifting all the bigger numbers along. Binary search finds where a number belongs quickly, but it does not make room for it. A single heap gives one end of the line, never the middle.

3The brute force, sorting again after every arrival

The honest first attempt, the brute force, follows the definition. We keep every number in a list. When a number arrives we add it, sort the whole list, and read the middle by position. It is short, it is clearly correct, and it is a good thing to say first in an interview.

By hand, after 5 the list is [5]. After 15, sorting gives [5, 15], and we average positions 0 and 1. After 1 it is [1, 5, 15] and we read position 1. After 3 it is [1, 3, 5, 15], and after 8 it is [1, 3, 5, 8, 15]. We ran it, and it prints the same five medians as our hand work.

Java
static List<Integer> seen = new ArrayList<>();
static double addAndGetMedian(int x) {
seen.add(x);
Collections.sort(seen); // sort everything again, every time
int n = seen.size();
if (n % 2 == 1) return seen.get(n / 2); // odd count: the middle one
return ((long) seen.get(n / 2 - 1) + seen.get(n / 2)) / 2.0; // even: average the two
}

Now let us count. The five sorts handle 1, 2, 3, 4 and 5 numbers, 15 numbers in all, just to report five medians. With n numbers in the list, one sort costs O(n log n), read as order n times log n, and over a stream of n arrivals that adds up to O(n squared log n). For a hundred thousand numbers that is far too slow.

A middle step is to keep the list sorted and slide each new number into place with binary search. Finding the place is fast, but making room is not, because every bigger number shifts one step along, so each arrival is still O(n).

So where is the waste? Before each arrival the list was already sorted, and we sorted it again. Worse, we kept the exact position of every number when we only ever read the one or two in the middle. In the photograph, we re-lined the whole class to find one child.

4Getting to two halves in two heaps

Let us keep only what the median needs. We split the numbers into a lower half, called low, and an upper half, called high, so that every number in low is at most every number in high. Inside each half the order does not matter. We only need quick access to the largest number in low and the smallest number in high, the two children standing next to the dividing line.

A heap gives exactly that. A max-heap is a tree in which every parent is at least as large as its children, so the largest value is always at the top, and it takes about log n steps to add a value or remove the top, because the tree is only log n levels tall. Java's PriorityQueue is such a heap; it is a min-heap normally and a max-heap when we give it Comparator.reverseOrder().

PictureInside low after all five numbers

A max-heap is a tree in which every parent is at least as large as its children, so the largest value is always at the top.

  1. 513
    low array
    [5, 1, 3]
    peek()
    5

    1Java keeps low in an array, [5, 1, 3], read as a tree: 5 on top, 1 and 3 below it. Only the top is in order, and that is all we need.

Next we fix a size rule, that low holds as many numbers as high, or exactly one more. With that rule, an odd total puts the median on top of low, and an even total makes it the average of the two tops. Reading the median is then one or two peeks, no searching at all.

Now the hard step, adding a number while keeping both rules. A beginner asks: how do we know which half the new number belongs to? Here is a tidy trick that avoids deciding. We always put the new number into low, and then at once move the top of low, its largest, into high. Whatever the newcomer was, the number that moves up is the largest on the lower side, so every number in low is still at most every number in high. If high now holds more than low, we move its top, its smallest, back down. So each add is one entry and at most two moves between the heaps, where a move is a poll from one heap and an offer to the other.

Why is the median right after this? The ordering rule makes the two tops the numbers on either side of the dividing line in sorted order. The size rule fixes how many numbers sit below the line. Together they mean the tops are exactly the middle one or two numbers, which is what the median needs.

The mistake most beginners make is to look after the sizes and forget the ordering, for example by putting each newcomer into whichever half is smaller. We ran that version on our stream. It gives 5, 10, 5 and 4, which look fine, but then 3 has gone into high and 8 into low, so the top of low is 8 while the top of high is 3, and the last median comes out as 8 instead of 5.

5Watching the two halves on the stream 5, 15, 1, 3, 8

The picture shows the two heaps after each important step. The top row is low, listed largest first, and the bottom row is high, listed smallest first, so the two tops face each other in the first column. The number that just moved is marked as looked at, and once a number has settled, the tops the median is read from are marked as the answer.

Watch the arrivals of 1 and 8. In both, the new number enters low, a number moves up, high becomes too big, and a number comes back down. That round trip is the whole method.

Step throughThe two halves as 5, 15, 1, 3 and 8 arrive

Top row: low, the max-heap, largest first. Bottom row: high, the min-heap, smallest first. A dash means empty.

  1. 5-
    arrived
    5
    sizes
    low 1, high 0
    median
    5.0

    15 enters low, moves up to high, and comes back, because high may not be bigger. low holds 5 alone, so the median is 5.

  2. 155-
    arrived
    15
    sizes
    low 2, high 0

    215 arrives and enters low. It is larger than 5, so it sits on top of the max-heap for a moment.

  3. 515
    arrived
    15
    sizes
    low 1, high 1
    median
    10.0

    3The top of low, 15, moves up to high. Now each half holds one number, so the median is the average of the two tops, (5 + 15) / 2.

  4. 1515
    arrived
    1
    sizes
    low 1, high 2

    41 arrives and enters low, under 5. Then the top of low, 5, moves up, so high holds 5 and 15 and is now the bigger half.

  5. 5115
    arrived
    1
    sizes
    low 2, high 1
    median
    5.0

    5high has two numbers and low only one, which breaks the size rule, so the top of high, 5, moves back down. The median is the top of low, 5.

  6. 53115
    arrived
    3
    sizes
    low 3, high 1

    63 arrives and enters low. The top of low is still 5, the largest of the lower half, so 5 is the one that will move up.

  7. 31515
    arrived
    3
    sizes
    low 2, high 2
    median
    4.0

    75 moves up to high. Each half holds two numbers, so no balancing is needed, and the median is (3 + 5) / 2 = 4.

  8. 315815
    arrived
    8
    sizes
    low 2, high 3

    88 arrives and enters low, where it becomes the top. It moves straight up to high, which now holds three numbers against two.

  9. 531815
    arrived
    8
    sizes
    low 3, high 2
    median
    5.0

    9high is bigger again, so its top, 5, moves down. low holds 5, 3, 1 and high holds 8, 15, and the median is the top of low, 5.

Look at the fourth and fifth frames. When 1 arrives, it goes into low under 5, and 5, the top, moves up into high. Now high holds 5 and 15 against low's single 1, so the size rule pulls 5 back down. The median is 5, the top of low, matching our hand work.

In the seventh frame the halves are [3, 1] and [5, 15], equal in size, so the median is (3 + 5) / 2 = 4. And in the last frame the halves are [5, 3, 1] and [8, 15]: the middle of 1, 3, 5, 8, 15 is the top of low. We never sorted anything; we only moved tops.

6The complete Java program

Here is the whole class. It keeps the two heaps as fields, adds numbers with add and answers with median. main runs the example stream, a stream of two negative numbers, and two copies of Integer.MAX_VALUE to show that the average does not overflow. Each comment shows what that line prints.

Java
import java.util.*;
public class MedianStream {
// low: the smaller half, as a max-heap. high: the larger half, as a min-heap.
private final PriorityQueue<Integer> low = new PriorityQueue<>(Comparator.reverseOrder());
private final PriorityQueue<Integer> high = new PriorityQueue<>();
void add(int x) {
low.offer(x); // every number enters through the lower half
high.offer(low.poll()); // the largest of the lower half moves up
if (high.size() > low.size()) { // keep low equal to high, or one bigger
low.offer(high.poll());
}
}
double median() {
if (low.isEmpty()) throw new IllegalStateException("no numbers yet");
if (low.size() > high.size()) return low.peek(); // odd count: the top of low
return ((long) low.peek() + high.peek()) / 2.0; // even count: average the two tops
}
public static void main(String[] args) {
var m = new MedianStream();
List<Double> medians = new ArrayList<>();
for (int x : new int[] {5, 15, 1, 3, 8}) {
m.add(x);
medians.add(m.median());
}
System.out.println(medians); // [5.0, 10.0, 5.0, 4.0, 5.0]
var negatives = new MedianStream();
negatives.add(-4);
negatives.add(-1);
System.out.println(negatives.median()); // -2.5
var big = new MedianStream();
big.add(Integer.MAX_VALUE);
big.add(Integer.MAX_VALUE);
System.out.println(big.median()); // 2.147483647E9
}
}

Let us read add in the order it runs. low.offer(x) puts the newcomer into the lower half. high.offer(low.poll()) takes the largest of the lower half and moves it up, which keeps the ordering rule. Then, if high has more numbers than low, low.offer(high.poll()) moves the smallest of the upper half back down, which keeps the size rule.

median checks for an empty stream first, so a caller gets a clear message instead of a crash from an empty heap. If low is bigger, the count is odd and the answer is low.peek(). Otherwise the count is even and we average the two tops.

Why the cast to long? Two copies of Integer.MAX_VALUE added as ints would wrap around to a negative number before the division. Widening one of them to long first makes the sum exact, and dividing by 2.0 gives a double. So main prints [5.0, 10.0, 5.0, 4.0, 5.0], then -2.5, then 2.147483647E9, which is Java's way of printing 2147483647.0.

7How much it costs, and the cases at the edges

Let us count on the example first. Each arrival made one entry into low and one or two moves. 5, 1 and 8 needed two moves and 15 and 3 needed one, so there were 5 entries and 8 moves, 21 offers and polls in all, each touching only a few levels of a tiny tree. In general an add is at most five heap operations of O(log n) each, so adding costs O(log n), and reading the median is O(1). A stream of n numbers costs O(n log n) in total, against O(n squared log n) for sorting every time.

The two heaps together hold every number, so the space is O(n). That cannot be avoided by any method, because a future median may depend on any number seen so far.

Comparing the ways to keep a running median
ApproachAddMedianSpace
Brute force: sort after every arrivalO(n log n)O(1)O(n)
Sorted list, binary search insertO(n) to shiftO(1)O(n)
Two balanced heapsO(log n)O(1)O(n)

Negative numbers and repeated numbers need no special code, because heaps only compare values. The largest ints are safe because the average is computed in long. A median asked for before any number arrives throws an IllegalStateException with a plain message. A single number gives itself as the median, because it ends in low.

8Follow-up questions

What if every number is between 0 and 100?

Then we can drop the heaps and keep an array of 101 counts, one box per possible value. Adding a number adds one to its box. To find the median we walk the boxes from 0, adding up counts until we pass the middle position, at most 101 steps, which is a constant. Knowing the range turns the problem into simple counting.

How would you find the median of each window of k numbers instead?

Now numbers leave as well as arrive, and a PriorityQueue takes O(k) to remove a number that is not on top. One fix is lazy deletion: we note leaving numbers in a hash map and throw them away only when they reach a top. Another is to replace each heap with a TreeMap of counts, which removes any value in O(log k).

Why not put the newcomer straight into the right half?

We can: compare it with the top of low and choose a side, then rebalance the sizes. It saves an operation now and then, but it has more cases to get right. Always going through low and moving its top up keeps the ordering rule true automatically, which is why it is safer under pressure.

9Conclusion

We kept a running median by splitting the numbers into a lower half in a max-heap and an upper half in a min-heap. Every newcomer goes into low, low's top moves up, and if high grows bigger its top comes back down, so the tops always sit on either side of the middle. Adding is O(log n), reading the median is O(1), and the space is O(n). The clue to remember is a changing collection where we only need what sits next to a boundary: keep each side in a heap with that boundary on top.

What to say in the interviewAbout 70 seconds aloud

Open with

Let me confirm the setup: numbers arrive one at a time, I report the median after each, an even count gives the average of the two middle values as a double, and values can be as large as Integer.MAX_VALUE.

Then, if they want more

Sorting after every arrival works but costs O(n log n) per number, and even a sorted list with binary search insert costs O(n) per number for the shifting.

Since I only ever need the middle, I will keep two heaps: a max-heap called low for the smaller half and a min-heap called high for the larger half, with low holding the same count as high or one more.

To add a number, I offer it to low, move low's top to high, and if high is now bigger, move high's top back to low. That keeps every number in low at most every number in high, and keeps the sizes balanced.

The median is low's top for an odd count, or the average of both tops in long arithmetic for an even count. Adding is O(log n), the median is O(1), and the space is O(n).

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 21 times in that collection. How it is counted
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Keep track of the median of a stream of numbers as each new number arrives.": https://scrivio-interview-library.netlify.app/data-structures/solutions/keep-track-of-the-median-of-a-stream-of-numbers-as-each-new-numb-183741/