Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half).
Problem: Maintain the median of a stream with two heaps (max-heap for the lower half, min-heap for the upper half).
import heapq
lo, hi, out = [], [], []
for x in [5, 15, 1, 3, 8]:
heapq.heappush(lo, -x)
heapq.heappush(hi, -heapq.heappop(lo))
if len(hi) > len(lo):
heapq.heappush(lo, -heapq.heappop(hi))
out.append(-lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2)
print(out)What is printed?- A. [5, 10.0, 5, 3, 5]
- B. [5, 10.0, 1, 4.0, 5]
- C. [5, 15, 5, 4.0, 8]
- D. [5, 10.0, 5, 4.0, 5]
Correct answer: D. [5, 10.0, 5, 4.0, 5]
Every number passes through lo into hi, and hi gives one back if it becomes larger, so lo always holds the smaller half (size equal or one more). Medians: 5; (5+15)/2 = 10.0; 5 of {1,5,15}; (3+5)/2 = 4.0 of {1,3,5,15}; 5 of {1,3,5,8,15}. O(log n) per insert, O(1) per median query.
More Coding Interview Problems questions
- Problem: Connect ropes into one; joining two ropes costs the sum of their lengths. Find the minimum total cost. python import heapq def…
- Problem: Return the k points closest to the origin (ties broken by smaller index). python import heapq pts = [(3, 3), (5, -1), (-2, 4)…
- Problem: Tasks labelled by letters each take 1 unit; the same task needs n idle units between repeats. Find the least total time. python…
- Problem: Merge overlapping booking intervals. python def merge(iv): iv.sort(); out = [] for s, e in iv: if out and s <= out[-1][1]…
- Problem: Remove the fewest meetings so that the rest do not overlap (meetings that only touch at an endpoint are fine). python def…
- Problem: Find the minimum number of meeting rooms needed for a list of meetings [start, end). python import heapq def rooms(iv)…