Bird
Raised Fist0
Interview Prepchallenge-problemshardAmazonFacebookGoogleMicrosoft

Find Median from Data Stream

Choose your preparation mode4 modes available
📋
Problem

Imagine you are monitoring live sensor data or stock prices and need to report the median value at any moment as new data arrives continuously.

Design a data structure that supports adding numbers from a data stream and finding the median of all elements so far. Implement two methods: addNum(int num) - adds a number to the data structure; findMedian() - returns the median of all elements added so far. The median is the middle value in an ordered integer list. If the size of the list is even, the median is the average of the two middle numbers.

1 ≤ number of addNum calls ≤ 10^5-10^5 ≤ num ≤ 10^5At least one element will be present before calling findMedian
Edge cases: Only one element added → median is that elementAll elements are the same → median is that elementLarge number of elements with duplicates → median calculation remains correct
</>
IDE
class MedianFinder: def __init__(self): pass def addNum(self, num: int) -> None: pass def findMedian(self) -> float: passpublic class MedianFinder { public MedianFinder() {} public void addNum(int num) {} public double findMedian() { return 0; } }class MedianFinder { public: MedianFinder() {} void addNum(int num) {} double findMedian() { return 0; } };class MedianFinder { constructor() {} addNum(num) {} findMedian() { return 0; } }
class MedianFinder:
    def __init__(self):
        # Write your solution here
        pass
    def addNum(self, num: int) -> None:
        pass
    def findMedian(self) -> float:
        pass
public class MedianFinder {
    public MedianFinder() {
        // Write your solution here
    }
    public void addNum(int num) {
    }
    public double findMedian() {
        return 0;
    }
}
#include <vector>
using namespace std;

class MedianFinder {
public:
    MedianFinder() {
        // Write your solution here
    }
    void addNum(int num) {
    }
    double findMedian() {
        return 0;
    }
};
class MedianFinder {
    constructor() {
        // Write your solution here
    }
    addNum(num) {
    }
    findMedian() {
        return 0;
    }
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: Median values off by one or incorrect averagesNot balancing the two heaps properly after insertion✅ After each addNum, rebalance heaps so their sizes differ by at most one
Wrong: Median is always the last inserted element or first elementUsing a greedy approach that does not maintain order or balance✅ Use two heaps to maintain lower and upper halves and compute median from heap tops
Wrong: Median incorrect when duplicates are presentIgnoring duplicates or treating them as single elements✅ Insert all duplicates into heaps and balance normally
Wrong: TLE on large inputsSorting entire list on every addNum call✅ Implement two heaps approach for O(log n) insertion and O(1) median retrieval
Wrong: Median calculation causes integer overflow or wrong averagingUsing integer division or not using float/double for median✅ Use float/double type and compute average as (a + b) / 2.0
✓
Test Cases
t1_01basic
Input["addNum(1)","addNum(2)","findMedian()","addNum(3)","findMedian()"]
Expected[1.5,2]

After adding 1 and 2, the sorted list is [1,2], median is (1+2)/2=1.5. After adding 3, list is [1,2,3], median is 2.

t1_02basic
Input["addNum(5)","addNum(15)","addNum(1)","findMedian()","addNum(3)","findMedian()"]
Expected[5,4]

After adding 5,15,1 the sorted list is [1,5,15], median is 5. After adding 3, list is [1,3,5,15], median is (3+5)/2=4.

t2_01edge
Input["addNum(10)","findMedian()"]
Expected[10]

Only one element added, median is that element itself.

t2_02edge
Input["addNum(7)","addNum(7)","addNum(7)","findMedian()"]
Expected[7]

All elements are the same, median is that element.

t2_03edge
Input["addNum(-100000)","addNum(100000)","findMedian()"]
Expected[0]

Elements at boundary values, median is average of -100000 and 100000 = 0.

t3_01corner
Input["addNum(1)","addNum(2)","addNum(3)","addNum(4)","addNum(5)","findMedian()"]
Expected[3]

Sequential increasing numbers, median is middle element 3.

t3_02corner
Input["addNum(1)","addNum(1)","addNum(1)","addNum(1)","findMedian()"]
Expected[1]

Repeated identical elements, test for confusion between 0/1 knapsack style counting and median calculation.

t3_03corner
Input["addNum(100000)","addNum(-100000)","addNum(0)","addNum(99999)","addNum(-99999)","findMedian()"]
Expected[0]

Mixed large positive and negative numbers, median is 0 after sorting [-100000,-99999,0,99999,100000].

t4_01performance
Input["addNum(0)","addNum(1)","addNum(2)","addNum(3)","addNum(4)","addNum(5)","addNum(6)","addNum(7)","addNum(8)","addNum(9)","addNum(10)","addNum(11)","addNum(12)","addNum(13)","addNum(14)","addNum(15)","addNum(16)","addNum(17)","addNum(18)","addNum(19)","addNum(20)","addNum(21)","addNum(22)","addNum(23)","addNum(24)","addNum(25)","addNum(26)","addNum(27)","addNum(28)","addNum(29)","addNum(30)","addNum(31)","addNum(32)","addNum(33)","addNum(34)","addNum(35)","addNum(36)","addNum(37)","addNum(38)","addNum(39)","addNum(40)","addNum(41)","addNum(42)","addNum(43)","addNum(44)","addNum(45)","addNum(46)","addNum(47)","addNum(48)","addNum(49)","addNum(50)","addNum(51)","addNum(52)","addNum(53)","addNum(54)","addNum(55)","addNum(56)","addNum(57)","addNum(58)","addNum(59)","addNum(60)","addNum(61)","addNum(62)","addNum(63)","addNum(64)","addNum(65)","addNum(66)","addNum(67)","addNum(68)","addNum(69)","addNum(70)","addNum(71)","addNum(72)","addNum(73)","addNum(74)","addNum(75)","addNum(76)","addNum(77)","addNum(78)","addNum(79)","addNum(80)","addNum(81)","addNum(82)","addNum(83)","addNum(84)","addNum(85)","addNum(86)","addNum(87)","addNum(88)","addNum(89)","addNum(90)","addNum(91)","addNum(92)","addNum(93)","addNum(94)","addNum(95)","addNum(96)","addNum(97)","addNum(98)","addNum(99)","findMedian()"]
⏱ Performance - must finish in 2000ms

n=100 addNum calls followed by findMedian; O(log n) per addNum and O(1) findMedian must complete within 2 seconds.

Practice

(1/5)
1. Given the following code snippet and inputs, what is the final returned value of W after executing findMaxCapital(2, 0, [1, 2, 3], [0, 1, 1])?
easy
A. 3
B. 4
C. 5
D. 2

Solution

  1. Step 1: Trace first iteration with W=0

    Projects with capital ≤0: only (0,1). Move profit 1 to max heap. Pop max profit 1, W=0+1=1.
  2. Step 2: Trace second iteration with W=1

    Projects with capital ≤1: (1,2) and (1,3). Move profits 2 and 3 to max heap. Pop max profit 3, W=1+3=4.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Final capital after 2 projects is 4 [OK]
Hint: Track heap contents and W updates carefully [OK]
Common Mistakes:
  • Forgetting to push all affordable projects each iteration
  • Off-by-one error in loop iterations
  • Confusing min-heap and max-heap usage
2. You are given an array of integers where you can perform operations to minimize the difference between the maximum and minimum elements. The operations allowed are doubling odd numbers once and halving even numbers multiple times. Which algorithmic approach guarantees finding the minimum possible deviation efficiently?
easy
A. Using a max-heap to iteratively reduce the maximum element while tracking the minimum
B. Brute force recursion trying all combinations of doubling and halving
C. Sorting the array and using a sliding window to find the minimal range
D. Dynamic programming to store states of all possible values after operations

Solution

  1. Step 1: Understand problem constraints and operations

    The problem allows doubling odd numbers once and halving even numbers multiple times to minimize deviation.
  2. Step 2: Identify approach that efficiently tracks max and min values

    Using a max-heap allows quick access to the current maximum, which can be reduced by halving, while tracking the minimum seen so far.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Max-heap approach efficiently updates max and min values [OK]
Hint: Max-heap efficiently tracks max element for reduction [OK]
Common Mistakes:
  • Thinking sorting + two pointers always works despite operations changing values
  • Assuming brute force is feasible for large inputs
  • Believing DP is needed despite no overlapping subproblems
3. Consider the following buggy code for finding employee free time. Which line contains the subtle bug that causes incorrect free time intervals?
def employeeFreeTime(schedule):
    intervals = [iv for employee in schedule for iv in employee]
    intervals.sort(key=lambda x: x[0])
    free_times = []
    prev_end = intervals[0][1]
    for i in range(1, len(intervals)):
        start, end = intervals[i]
        if start >= prev_end:
            free_times.append([prev_end, start])
        prev_end = max(prev_end, end)
    return free_times
medium
A. Line with intervals.sort(key=lambda x: x[0])
B. Line with prev_end = max(prev_end, end)
C. Line with if start >= prev_end:
D. Line with prev_end = intervals[0][1]

Solution

  1. Step 1: Identify condition for free time

    Free time exists only if start > prev_end, not when start == prev_end, because zero-length intervals are invalid.
  2. Step 2: Analyze buggy condition

    The condition uses start >= prev_end, which incorrectly adds zero-length intervals when start == prev_end.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Changing >= to > fixes zero-length interval bug [OK]
Hint: Free time intervals must have positive length [OK]
Common Mistakes:
  • Using >= instead of > for gap detection
  • Not sorting intervals before merging
  • Incorrectly updating prev_end
4. Consider the following buggy code snippet for minimizing deviation. Which line contains the subtle bug that can cause incorrect results?
import heapq

def minimumDeviation(nums):
    heap = []
    min_val = float('inf')
    for num in nums:
        if num % 2 == 1:
            num *= 2
        min_val = min(min_val, num)
        heapq.heappush(heap, num)  # BUG: pushing positive num instead of negative

    min_dev = float('inf')
    while True:
        max_val = -heapq.heappop(heap)
        min_dev = min(min_dev, max_val - min_val)
        if max_val % 2 == 0:
            max_val //= 2
            min_val = min(min_val, max_val)
            heapq.heappush(heap, -max_val)
        else:
            break
    return min_dev
medium
A. Line updating min_val after halving max_val
B. Line pushing elements into heap (heapq.heappush(heap, num))
C. Line popping max_val from heap
D. Line breaking loop when max_val is odd

Solution

  1. Step 1: Identify heap usage

    The algorithm uses a max-heap simulated by pushing negative values.
  2. Step 2: Locate bug in heap push

    Line pushing positive num instead of negative breaks max-heap property, causing incorrect max_val extraction.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Heap must store negative values to simulate max-heap [OK]
Hint: Max-heap simulated by pushing negatives; pushing positives breaks logic [OK]
Common Mistakes:
  • Using min-heap without negation for max element
  • Not updating min_val after halving
  • Trying to halve odd numbers
5. The following code attempts to rearrange a string so that the same characters are at least k distance apart. Identify the line containing the subtle bug that can cause invalid output or failure.
medium
A. Line: heapq.heapify(max_heap) # heapify should be replaced with sort
B. Line: if k == 0: return s # should handle k=1 differently
C. Line: queue.append((char, count)) # decrement count missing
D. Line: if front_count < 0: heapq.heappush(max_heap, (front_count, front_char)) # should check for <= 0

Solution

  1. Step 1: Identify decrement of count

    The algorithm must decrement the count of the character after using it, i.e., count + 1 since counts are negative.
  2. Step 2: Locate missing decrement

    In the buggy line, count is appended without incrementing, so the character count never decreases, causing infinite loops or invalid results.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Correct decrement is critical to track usage [OK]
Hint: Check if character count is updated after usage [OK]
Common Mistakes:
  • Forgetting to decrement count after popping from heap
  • Misusing queue length to enforce k-distance
  • Incorrect heap operations or conditions
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard