Data Structures & AlgorithmsVery hardProduct company OA
Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time limit 2 s. Which approach passes?
- A. Keep the window in a Python list and call sorted() after every arrival – O(n·k log k) is fine for 2 seconds
- B. Two heaps (max-heap for the lower half, min-heap for the upper half) with lazy deletion of expired values and size rebalancing – O(n log k)
- C. Two heaps without any deletion: expired values sink to the bottom and never affect the top
- D. A running average of the window, because for latency data the mean equals the median
Correct answer: B. Two heaps (max-heap for the lower half, min-heap for the upper half) with lazy deletion of expired values and size rebalancing – O(n log k)
Re-sorting is about 2·10⁵ × 10⁵·17 ≈ 3·10¹¹ operations. Expired values do not sink in a heap – a large expired value can sit at the top of the min-heap and be reported as the median, so they must be removed: lazily (a 'to delete' counter checked when the value reaches the top, with balance computed from valid sizes) or with an order-statistics structure / two sorted multisets (C++ multiset) – both O(log k) per step. The mean is not the median for skewed data such as latencies.
More Coding Interview Problems questions
- Problem: A scoreboard calls a reading a 'leader' if it is strictly greater than every reading to its right (the last reading is always a…
- Problem: Return the squares of a sorted array (values may be negative) in non-decreasing order in O(n), filling the result from the back…
- Problem: A wallet starts with a positive balance s and then applies the day's changes in order. Find the minimum s such that the running…
- Problem: A warehouse aisle has shelves with weights; find the leftmost 'balance shelf' i such that the total weight strictly to its left…
- Problem: A street has n = 6 lamps, all starting at brightness 0. Each command (l, r, v) adds v to every lamp from l to r (0-based…
- Problem: A 3 × 4 grid of crop yields must answer 'total yield in rectangle (r1, c1)–(r2, c2)' in O(1) using a 2-D prefix table with one…