Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half).
Problem: Report the running median of a stream using a max-heap (lower half) and a min-heap (upper half).
import heapq
def medians(stream):
lo, hi, out = [], [], []
for x in stream:
heapq.heappush(lo, -x)
heapq.heappush(hi, -heapq.heappop(lo))
if len(hi) > len(lo): heapq.heappush(lo, -heapq.heappop(hi))
m = -lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2
out.append(f"{m:g}")
return " ".join(out)
print(medians([5, 15, 1, 3, 2, 8]))What is printed?- A. 5 10 5 4 2 4
- B. 5 10 5 4 3 4
- C. 5 10 1 3 2 2
- D. 5 10 5 3 3 4
Correct answer: B. 5 10 5 4 3 4
Sorted prefixes: [5] → 5; [5, 15] → 10; [1, 5, 15] → 5; [1, 3, 5, 15] → 4; [1, 2, 3, 5, 15] → 3; [1, 2, 3, 5, 8, 15] → (3 + 5)/2 = 4. Every push goes through both heaps so the max of the lower half never exceeds the min of the upper half.
More Coding Interview Problems questions
- Which statement about selecting the k-th smallest of n unsorted numbers is correct?
- Problem: Find the smallest divisor d such that Σ ceil(a[i] / d) ≤ threshold. python def smallestdiv(a, t): lo, hi = 1, max(a) while lo <…
- Problem: Buses i take time[i] minutes per trip and run independently and repeatedly. Find the minimum time for all buses together to…
- Problem: Use bisect to count how many readings lie in the closed range [2, 7]. python from bisect import bisectleft, bisectright a = [1…
- Problem: Vertical order traversal: group nodes by column (left child c − 1, right child c + 1); inside a column sort by row, then by…
- Problem: Zigzag level-order traversal (left to right, then right to left, alternating). python class T: def init(s, v): s.v, s.l, s.r = v…