Top 150 InterviewHard

Find Median From Data Stream

Detailed guide and Python implementation for the 'Find Median From Data Stream' problem.

Problem Statement

Hard

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.

Implement the MedianFinder class:

- MedianFinder() Initializes the MedianFinder object.

- addNum(num: int) Adds the integer num from the data stream to the data structure.

- findMedian() -> float Returns the median of all elements so far.

Input is a list of operations and arguments. Implement a function medianFinder(operations: list, arguments: list) -> list that returns a list of results (None for constructor/addNum, float for findMedian).

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

Examples

Example 1
Input
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
Output
[None, None, None, 1.5, None, 2.0]
Explanation

Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.

Need a Hint?
Consider using Heap / Priority Queue-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.