Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: For a stream of n = 10⁶ (user, timestamp) hits, answer 'how many hits in the last 300 seconds?' after each new hit (timestamps non-decreasing). Which structure gives amortised O(1)?
- A. A balanced BST – O(log n) is the best possible
- B. A deque of timestamps – push new hits at the back and pop expired ones from the front
- C. Recount the whole history each time
- D. A stack of timestamps
Correct answer: B. A deque of timestamps – push new hits at the back and pop expired ones from the front
Because timestamps arrive in order, expired hits are always at the front; each hit is pushed once and popped once, so the total work is O(n). A stack exposes the newest hit, not the oldest.
More Coding Interview Problems questions
- Problem: Implement a set that supports insert, delete and getRandom (uniformly random element) all in average O(1). Which combination works?
- Problem: Support 'add number' and 'find a pair summing to t' where adds are 10⁵ and finds are rare, versus the opposite workload. Which…
- Problem: Map each word of a 10⁶-word document to its frequency, then print words in alphabetical order. Which choice gives O(n log n) with…
- Problem: Count the number of distinct islands by shape in a grid (shapes match only by translation). python def distinct(g): R, C =…
- Problem: Count subarrays with at most k distinct values, then use it to count subarrays with exactly k distinct values. python from…
- Problem: Find the number of 'nice' subarrays containing exactly k odd numbers using prefix counts. python def nice(a, k): cnt = {0: 1}…