Top 150 Interviewハード

Find Median From Data Stream

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

問題提起

ハード

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

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。