Find Median from Data Stream - Watch the Algorithm Execute, Step by Step
Watching the algorithm step-by-step reveals how the two heaps maintain a balanced state to efficiently find the median at any point in the data stream.
Step 1/10
·Active fill★Answer cell
setup
insert
small_top
-1
0
insert
small_top
-1
0
large_top
2
1
compare
small_top
-1
0
large_top
2
1
compare
small_top
-1
0
large_top
2
1
Result: 1.5
insert
small_top
-1
0
large_top
2
1
3
2
Result: 1.5
rebalance
small_top
-2
0
-1
1
large_top
3
2
Result: 1.5
compare
small_top
-2
0
-1
1
large_top
3
2
Result: 2
record
small_top
-1
0
large_top
2
1
Result: 1.5
record
small_top
-2
0
-1
1
large_top
3
2
Result: 2
Key Takeaways
✓ Two heaps maintain a balanced partition of the data stream to efficiently compute median.
This balance is hard to see from code alone but is clear when watching heaps grow and shrink.
✓ Median calculation depends on heap sizes: average of tops if equal, top of larger heap if odd count.
Visualizing heap sizes and top elements clarifies why median formulas differ.
✓ Rebalancing moves elements between heaps to maintain size constraints after each insertion.
Seeing the actual element moved during rebalance helps understand the heap size invariants.
Practice
(1/5)
1. Consider the following Python code implementing the optimal DP solution for the stock problem with k transactions. What is the final output when calling maxProfit(1, [1, 5, 2])?
def maxProfit(k, prices):
n = len(prices)
if k >= n // 2:
profit = 0
for i in range(1, n):
profit += max(0, prices[i] - prices[i - 1])
return profit
next_dp = [[0, 0] for _ in range(k + 1)]
curr_dp = [[0, 0] for _ in range(k + 1)]
for i in range(n - 1, -1, -1):
for t in range(1, k + 1):
curr_dp[t][0] = max(-prices[i] + next_dp[t][1], next_dp[t][0])
curr_dp[t][1] = max(prices[i] + next_dp[t - 1][0], next_dp[t][1])
next_dp, curr_dp = curr_dp, next_dp
return next_dp[k][0]
print(maxProfit(1, [1, 5, 2]))
Maximum profit with 1 transaction is buying at 1 and selling at 5 -> profit 4 [OK]
Hint: Trace dp arrays backward to find max profit [OK]
Common Mistakes:
Confusing holding and not holding states
Off-by-one errors in indexing transactions
Misreading the final dp state to return
2. You need to transform one string into another using the minimum number of insertions, deletions, and substitutions. Which algorithmic approach guarantees finding the optimal solution efficiently?
easy
A. Greedy algorithm that replaces characters whenever they differ
B. Pure brute force recursion without memoization
C. Dynamic Programming that builds a table of subproblem solutions based on prefixes
D. Divide and conquer by splitting strings into halves and solving independently
Solution
Step 1: Understand problem requires minimum edits
The problem asks for minimum insertions, deletions, and substitutions to convert one string to another, which is a classic DP problem.
Dynamic Programming builds solutions for prefixes and combines them, ensuring optimality and polynomial time.
Final Answer:
Option C -> Option C
Quick Check:
DP table approach is standard for edit distance [OK]
Hint: Edit distance requires DP over prefixes [OK]
Common Mistakes:
Thinking greedy or divide-and-conquer works optimally
3. You are given two sorted arrays and need to find the median of their combined elements efficiently without fully merging them. Which approach guarantees the optimal time complexity for this problem?
easy
A. Merge both arrays completely and then find the median from the merged array.
B. Use binary search to partition the smaller array and find the correct partition in the other array.
C. Use a two-pointer approach to partially merge elements until the median position is reached.
D. Apply dynamic programming to store medians of subarrays and combine results.
Solution
Step 1: Understand the problem constraints
The problem requires finding the median of two sorted arrays without fully merging them to achieve better than O(m+n) time.
Step 2: Identify the optimal approach
Binary search on the smaller array to find a partition that balances elements on both sides guarantees O(log(min(m,n))) time, which is optimal.
Final Answer:
Option B -> Option B
Quick Check:
Binary search on partition is the known optimal solution [OK]
Hint: Optimal median uses binary search on smaller array [OK]
Common Mistakes:
Assuming full merge is necessary
Using two pointers without binary search
Confusing DP with median finding
4. Examine the following buggy code snippet for Expression Add Operators. Which line contains the subtle bug that causes incorrect results on inputs with leading zeros?
medium
A. Line appending operator '+': path.append('+')
B. Line checking for leading zero: if i != index and num[index] == '0': break
C. Line converting substring to int: curr = int(curr_str)
D. Line resetting path after recursion: path[:] = path[:length_before]
Solution
Step 1: Identify handling of leading zeros
The check for leading zeros is inside the else block, after the first index, which is correct placement.
Step 2: Confirm correctness of the check
The condition "if i != index and num[index] == '0': break" prevents numbers like "05" but is placed after the first index check, which causes it to be skipped for the very first number, allowing invalid leading zeros there.
Final Answer:
Option B -> Option B
Quick Check:
Leading zero check must be before substring parsing to avoid invalid numbers [OK]
Hint: Leading zero check must be before int conversion and recursion [OK]
Common Mistakes:
Placing leading zero check too late
Not breaking early on invalid substrings
5. Consider the following buggy code snippet for merging two skylines. Which line contains the subtle bug that can cause incorrect skyline output by adding redundant points or missing height changes?
medium
A. Line where maxH is computed with max(h1, h2)
B. Line where merged appends [x, maxH] without checking last height
C. Line where i and j are incremented in the else block
D. Line where h1 and h2 are initialized to 0 at the start
Solution
Step 1: Identify the bug
The code appends every point without checking if the height changed, causing redundant points.
Step 2: Correct approach
Appending should happen only if merged is empty or last height differs from maxH to avoid duplicates.