Find Median From Data Stream
Detailed guide and Python implementation for the 'Find Median From Data Stream' problem.
Problem Statement
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).
- •-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
operations = ["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"], arguments = [[], [1], [2], [], [3], []]
[None, None, None, 1.5, None, 2.0]
Initialize. Add 1, 2. Median is 1.5. Add 3. Median is 2.0.
Need a Hint?
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.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Remove Duplicates From a List in Python
Learn how to remove duplicates from a list in Python while maintaining or ignoring order. Compare set conversions, dict keys, and loop methods.
Python Collections & Data Structures
Complete guide to Python collections module and native data structures. Learn lists, dicts, sets, tuples, deques, and namedtuples.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.