101 Logo
onenoughtone

Problem Statement

Continuous Median Tracker

You're building a data analytics system that needs to continuously track the median value of a stream of numbers.

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.

For example:

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

Design a data structure that supports the following operations:

  • void addNum(int num) - Add an integer from the data stream to the data structure.
  • double findMedian() - Return the median of all elements so far.

Examples

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(); // return 1.5 (i.e., (1 + 2) / 2) medianFinder.addNum(3); // arr = [1, 2, 3] medianFinder.findMedian(); // return 2.0

Constraints

  • -10^5 <= num <= 10^5
  • There will be at least one element in the data structure before calling findMedian.
  • At most 5 * 10^4 calls will be made to addNum and findMedian.

Problem Breakdown

To solve this problem, we need to:

  1. The key challenge is efficiently maintaining the median as new numbers are added to the stream
  2. Sorting the entire array after each insertion would be inefficient (O(n log n) time complexity)
  3. Using two heaps (a max heap for the smaller half and a min heap for the larger half) allows for O(log n) insertion and O(1) median retrieval
  4. The heaps need to be balanced so that their sizes differ by at most 1
  5. For the follow-up questions, counting sort or bucket sort can be used when the range of numbers is limited
  6. When most numbers are in a limited range, a combination of counting sort for the limited range and a regular approach for outliers can be efficient
ProblemSolutionCode
101 Logo
onenoughtone