Blind 75
39 / 75Free practice

Find Median From Data Stream

Hard · Heaps

Jump to code

Support adding integers one at a time and finding the median of all values seen. Median queries occur only after at least one insertion; average the middle pair for even counts.

Examples

Example 1

operations = ["addNum","addNum","findMedian","addNum","findMedian"]
values = [1,2,0,3,0]

Output: [1.5,2]

Example 2

operations = ["addNum","findMedian"]
values = [5,0]

Output: [5]

Constraints

  • -100,000 <= num <= 100,000
  • findMedian will only be called after adding at least one integer to the data structure.

Function contract

Implement MedianFinder with addNum(num) and findMedian(). Each case starts a new instance. values[i] supplies addNum; its placeholder is ignored for findMedian. Only median queries produce output.

Need a hint?

Keep the smaller half and larger half separately.

Asked in real interviews

Candidates reported versions of Find Median From Data Stream from these company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 10 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    "addNum",
    "addNum",
    "findMedian",
    "addNum",
    "findMedian"
  ],
  [
    1,
    2,
    0,
    3,
    0
  ]
]
Expected
[
  1.5,
  2
]
Case 2
Input
[
  [
    "addNum",
    "findMedian"
  ],
  [
    5,
    0
  ]
]
Expected
[
  5
]
Case 3
Input
[
  [
    "addNum",
    "addNum",
    "addNum",
    "findMedian"
  ],
  [
    2,
    3,
    4,
    0
  ]
]
Expected
[
  3
]
Case 4
Input
[
  [
    "addNum",
    "addNum",
    "findMedian"
  ],
  [
    -1,
    -2,
    0
  ]
]
Expected
[
  -1.5
]
Case 5
Input
[
  [
    "addNum",
    "findMedian",
    "addNum",
    "findMedian",
    "addNum",
    "findMedian"
  ],
  [
    10,
    0,
    20,
    0,
    30,
    0
  ]
]
Expected
[
  10,
  15,
  20
]

Drafts are saved per language in this browser when storage is available.