15% off all plans & roadmaps Use code

See plans

Find Median from Data Stream

Updated

TL;DR: Design a structure that accepts numbers one at a time and returns the median of everything seen so far. Keep the smaller half in a max-heap and the larger half in a min-heap, so the median sits at the heap tops.

Problem

The median is the middle value of an ordered list of integers. When the list has an even number of elements, there is no single middle value, so the median is the mean of the two middle values.

  • For arr = [2,3,4], the median is 3.
  • For arr = [2,3], the median is (2 + 3) / 2 = 2.5.

Implement the MedianFinder class:

  • MedianFinder() creates an empty MedianFinder object.
  • void addNum(int num) adds the integer num from the data stream to the structure.
  • double findMedian() returns the median of all elements added so far. Answers within 10^-5 of the true value are accepted.

Example 1

Input: ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]
[[], [1], [2], [], [3], []]
Output: [null, null, null, 1.5, null, 2.0]
Explanation:
MedianFinder medianFinder = new MedianFinder();
medianFinder.addNum(1);    // arr = [1]
medianFinder.addNum(2);    // arr = [1, 2]
medianFinder.findMedian(); // returns 1.5, which is (1 + 2) / 2
medianFinder.addNum(3);    // arr = [1, 2, 3]
medianFinder.findMedian(); // returns 2.0

Constraints

  • -10^5 <= num <= 10^5
  • At least one element is in the structure before findMedian is called.
  • At most 5 * 10^4 calls are made to addNum and findMedian combined.

Constraints that matter

  • Up to 5 * 10^4 calls mix addNum and findMedian. If every call re-sorts a list of up to 5 * 10^4 numbers, the work reaches roughly 10^9 steps in the worst case, so sorting inside findMedian is risky.
  • The values are bounded by 10^5 in magnitude, so the sum of two values fits in a 32-bit int. You still divide by 2.0, not 2, to keep the fraction.
  • findMedian is only called on a non-empty structure, so you never need to handle an empty median or return a placeholder.
  • The answer tolerance is 10^-5, but every median here is a multiple of 0.5, so the double you return is exact. No rounding tricks are needed.
  • The stream is online. You cannot sort once at the end, so the structure must stay ready for a query after every insert.

View on LeetCode

Hints

Hint 1

This is the two heaps pattern.

Hint 2

Store every number in a plain list.

Solution

Intuition

This is the two heaps pattern. The median depends on only one or two elements: the largest value of the lower half and the smallest value of the upper half. You do not need the full sorted order, only the boundary between the halves.

Picture a line of people sorted by height, with the tallest of the shorter half standing at the front of the left group and the shortest of the taller half at the front of the right group. The max-heap is the left group's front person, and the min-heap is the right group's front person, so the median is always found at those two front spots without re-sorting the line.

That points to two heaps. A max-heap holds the smaller half, so its top is the largest of the small values. A min-heap holds the larger half, so its top is the smallest of the large values. Both tops are readable in O(1).

Two rules keep this valid. First, every value in the max-heap is less than or equal to every value in the min-heap. Second, the max-heap holds either the same number of elements as the min-heap or exactly one more. With these rules, an odd count puts the median on top of the max-heap, and an even count puts it between the two tops.

Each insert costs O(log n) because a heap push or pop touches one root-to-leaf path. A sorted array would pay O(n) per insert to shift elements. The heaps pay only for the part of the order they actually need.

Watch the pattern animation

Worked example

Input: commands = ["MedianFinder", "addNum", "findMedian"], arguments = [[], [-100000], []]
Output: [null, null, -100000.0]
Explanation: The structure starts empty. After addNum(-100000) it holds one element, so that element is the median. findMedian returns -100000.0, the only value present.

Approach 1: Sort on every query

Store every number in a plain list. addNum appends, and findMedian sorts the list and reads the middle.

You write this first because it follows the definition of the median word for word. It is correct for every input.

Steps

  1. Keep a list nums, empty at the start.
  2. In addNum, append the new number to the end of nums.
  3. In findMedian, sort nums in ascending order.
  4. Let n be the length. If n is odd, return nums[n / 2] as a double.
  5. If n is even, return the mean of nums[n / 2 - 1] and nums[n / 2], dividing by 2.0.

Dry run

On the example: addNum(-100000) appends, so nums = [-100000]. findMedian() sorts the one-element list, which stays [-100000]. Here n = 1 is odd, so the answer is nums[0] = -100000, returned as -100000.0. That matches the expected output.

On a longer stream such as 1, 2, 3, every query would sort [1, 2, 3] again from scratch, even though only one value arrived since the last sort.

Complexity

TimeaddNum O(1), findMedian O(n log n)
SpaceO(n)

Here n is the number of elements added so far. Appending touches one slot, so addNum is O(1) amortized. Sorting n elements costs O(n log n) comparisons, and findMedian pays that on every call. With 5 * 10^4 interleaved calls, the total reaches about n^2 log n work in the worst case. Space is O(n), since the list stores each element once.

PythonTested in our runner

from typing import List, Optional

class MedianFinder:
    def __init__(self):
        self.nums = []

    def addNum(self, num: int) -> None:
        self.nums.append(num)

    def findMedian(self) -> float:
        self.nums.sort()
        n = len(self.nums)
        if n % 2 == 1:
            return float(self.nums[n // 2])
        return (self.nums[n // 2 - 1] + self.nums[n // 2]) / 2.0

Approach 2: Sorted list with binary search insert

What's slow: the first approach sorts the whole list on every query. The list was already sorted at the previous query, and only one value arrived since. That repeated sort is the wasted work.

The insight that fixes it: keep the list sorted at all times. Binary search finds the insert position in O(log n), and inserting there keeps the order. Then findMedian is a plain index read.

The cost moves to addNum. Inserting into the middle of an array shifts every later element, which is O(n). The lookup got faster, but the insert did not become cheap.

Steps

  1. Keep a list nums that is always sorted ascending.
  2. In addNum, binary search for the first position whose value is not less than num.
  3. Insert num at that position, shifting later elements right.
  4. In findMedian, let n be the length of nums.
  5. If n is odd, return nums[n / 2] as a double.
  6. If n is even, return the mean of nums[n / 2 - 1] and nums[n / 2].

Dry run

On the example: addNum(-100000) searches an empty list. The insert position is 0, so nums = [-100000]. findMedian() sees n = 1, which is odd, and returns nums[0] = -100000.0.

On the stream 1, 2, 3: inserting 2 into [1] lands at index 1, giving [1, 2], and the median is 1.5. Inserting 3 lands at index 2, giving [1, 2, 3], and the median is nums[1] = 2.0.

Complexity

TimeaddNum O(n), findMedian O(1)
SpaceO(n)

Here n is the number of elements stored. Binary search takes O(log n) comparisons, but the insert shifts up to n elements, so addNum is O(n) overall. findMedian reads one or two indexes, which is O(1). The shifting is a fast memory move, so this passes in practice. Its growth rate is still worse than the heap version. The list holds each element once, so space is O(n).

PythonTested in our runner

from typing import List, Optional
import bisect

class MedianFinder:
    def __init__(self):
        self.nums = []

    def addNum(self, num: int) -> None:
        # keeps the list sorted; the insert shifts elements in O(n)
        bisect.insort(self.nums, num)

    def findMedian(self) -> float:
        n = len(self.nums)
        if n % 2 == 1:
            return float(self.nums[n // 2])
        return (self.nums[n // 2 - 1] + self.nums[n // 2]) / 2.0
Two Heaps for Median Finding pattern infographic for Find Median from Data Stream

Solution pattern

Two Heaps for Median Finding

Part of Heap (Priority Queue) Patterns

Approach 3: Two heapsOptimalTwo Heaps for Median Finding

What's slow: the sorted list pays O(n) per insert to keep every element in order. The median needs only the two elements next to the middle, so most of that order is never read.

The insight that fixes it: split the data into a lower half and an upper half. Store the lower half in a max-heap small and the upper half in a min-heap large. Keep small the same size as large, or one larger. The median is then small.top for an odd count, or the mean of both tops for an even count.

For an insert, push the number into small, pop the largest of small, and push that into large. This guarantees the ordering rule, because the value that crosses over is the largest of the small side. If large now has more elements, move its smallest back to small. That is at most three heap operations.

Why it is correct. The invariant is that every value in the max-heap is at most every value in the min-heap, and the max-heap has the same size or one more. Each insert pushes the new value through the small side first, so the value that moves across is always the largest of the lower half. That keeps the boundary correct, so the two tops are always the middle elements of the full sorted data.

Steps

  1. Create small, a max-heap for the lower half, and large, a min-heap for the upper half.
  2. In addNum, push num into small.
  3. Pop the largest value from small and push it into large.
  4. If large has more elements than small, pop the smallest from large and push it into small.
  5. In findMedian, if small has more elements, return its top as a double.
  6. Otherwise the sizes are equal, so return the mean of the two tops using division by 2.0.
  7. In languages with only a min-heap, such as Python, store negated values in small to act as a max-heap.

Dry run

Trace of the example. small is shown as its real values, although Python stores them negated.

StepActionsmall (max-heap)large (min-heap)Result
0Start[][]none
1addNum(-100000): push into small[-100000][]none
2Pop top of small, push into large[][-100000]none
3large (1) is bigger than small (0), so move top of large back[-100000][]none
4findMedian(): small is larger, return its top[-100000][]-100000.0

The output is -100000.0, as expected.

On the longer stream 1, 2, 3 the same moves give: after 1, small = [1]. After 2, small = [1], large = [2], and the median is 1.5. After 3, the 3 goes through small into large, which then holds [2, 3], so 2 moves back. The result is small = [1, 2], large = [3], and the median is 2.0.

Complexity

TimeaddNum O(log n), findMedian O(1)
SpaceO(n)

Here n is the number of elements added so far. addNum does at most three heap pushes or pops. Each one walks a single root-to-leaf path of height at most log n, so it costs O(log n). findMedian reads at most two heap tops, which is O(1). Every element lives in exactly one heap, so space is O(n). Over 5 * 10^4 calls the total is about 5 * 10^4 * 16 heap steps, far below the sorting cost.

PythonTested in our runner

from typing import List, Optional
import heapq

class MedianFinder:
    def __init__(self):
        self.small = []  # max-heap of the lower half, stored as negated values
        self.large = []  # min-heap of the upper half

    def addNum(self, num: int) -> None:
        heapq.heappush(self.small, -num)
        # move the largest of the lower half to the upper half
        top = -heapq.heappop(self.small)
        heapq.heappush(self.large, top)
        # keep small the same size as large, or one bigger
        if len(self.large) > len(self.small):
            top = heapq.heappop(self.large)
            heapq.heappush(self.small, -top)

    def findMedian(self) -> float:
        if len(self.small) > len(self.large):
            return float(-self.small[0])
        return (-self.small[0] + self.large[0]) / 2.0

Common mistakes

  • Using two default min-heaps in Java or C++. The lower half needs its largest element on top, so use Collections.reverseOrder() or priority_queue<int>, or negate values in Python.
  • Writing (a + b) / 2 with two ints. Integer division drops the .5 and findMedian returns 1 instead of 1.5. Divide by 2.0.
  • Dropping the final rebalance step, if large.size() > small.size(). Without it large can grow larger than small, and small.top is no longer the middle element for odd counts.
  • Pushing the new number straight into one heap by size alone. A small number can land in large and break the ordering rule. Route it through small first, then pop the top across.
  • Reading the tops when a heap is empty. After the first addNum, large is empty again, so findMedian must check sizes before touching large.top. With an odd count only small has data.
  • Sorting a JavaScript array with nums.sort() and no comparator. It compares as strings, so -100000 and 99 end up in the wrong order. Pass (a, b) => a - b.

Edge cases

  • One element, such as addNum(-100000) then findMedian: return that value as -100000.0, with large empty.
  • Two elements, such as 1 and 2: sizes are equal, so return the mean 1.5 and not an integer.
  • All elements equal, such as five copies of 7: the median is 7.0, and ties must not break the ordering rule.
  • Negative and positive values mixed, such as -1, 0, 1: the median is 0.0. Check that negation in the Python version does not confuse 0.
  • Values at both extremes, -100000 and 100000: the median is 0.0, and the sum of the tops stays within int range.
  • A query after every insert on 5 * 10^4 numbers: the heap version must stay fast, which it does at O(log n) per insert.

Follow-ups interviewers ask

If every number in the stream is an integer in the range [0, 100], how would you optimize the solution?
Use a counting array of 101 buckets. addNum increments one bucket and is O(1). findMedian walks the buckets, accumulating counts until it reaches the middle position. That is at most 101 steps, so O(1) for a fixed range. Space is O(1) as well.
If 99% of the numbers are in [0, 100] and the rest are outliers, what changes?
Keep the 101 counting buckets for the common range. Also keep a count of values below 0 and a count of values above 100, plus the actual outlier values only if needed. The median almost always falls inside [0, 100], so you walk the buckets after adding the below-range count. In the rare case it falls in an outlier region, you need the outliers stored in a sorted structure or two small heaps.
Can you support removing an element, or a sliding window median?
Heaps do not delete arbitrary values efficiently. Use lazy deletion: mark the value as removed in a hash map and discard it when it reaches a heap top, while tracking the logical sizes of each heap. Another option is an ordered multiset with an iterator to the middle element. Both keep each operation at O(log n).

Find Median from Data Stream FAQ

What is the time complexity of Find Median from Data Stream?

With two heaps, addNum is O(log n) and findMedian is O(1), where n is the number of elements added so far. Space is O(n) because every element sits in one of the heaps. Sorting on every query costs O(n log n) per findMedian instead.

Why use two heaps for Find Median from Data Stream?

The median depends only on the largest value of the lower half and the smallest value of the upper half. A max-heap and a min-heap expose exactly those two values in O(1) and absorb new values in O(log n). A sorted array pays O(n) per insert to keep order you never read.

How do you do Find Median from Data Stream in Python?

Python's heapq is a min-heap only, so store negated numbers in the lower-half heap to make it behave as a max-heap. Push into small as -num, pop its top and push the negation back into large, then rebalance if large is bigger. Return -small[0] for odd counts, or (-small[0] + large[0]) / 2.0 for even counts.

How do you do Find Median from Data Stream in Java?

Use PriorityQueue<Integer> for both heaps. Create the lower half with Collections.reverseOrder() so its top is the maximum. Divide the sum of the tops by 2.0 so the result stays a double.

Can Find Median from Data Stream be solved in O(1) extra space?

No, not in general. The structure must remember every number, because a later number can shift which value is in the middle. That needs O(n) space. Only the bounded-range follow-up reaches O(1) space, using a fixed counting array.

Why does the sorting solution for LeetCode 295 time out?

It re-sorts the whole list on every findMedian, costing O(n log n) each time. With up to 5 * 10^4 calls alternating between adds and queries, the total work grows as roughly n^2 log n. Keeping the data partly ordered in two heaps avoids that repeated sort.

Asked at

See which companies ask this — Pro

Practise it