Data Structures & AlgorithmsHardGoogle · Flipkart interview
Reservoir sampling keeps k = 2 items from a stream of n = 10 items: the first 2 fill the reservoir, and item i (i > 2) is admitted with probability 2/i, replacing a uniformly random slot. What is the probability that item 4 is in the final sample?
- A. 1/10
- B. 1/5
- C. 1/2
- D. 2/9
Correct answer: B. 1/5
Item 4 is admitted with probability 2/4 and then survives each later item j with probability 1 − (2/j)(1/2) = (j − 1)/j. The product telescopes: (2/4) × (4/5)(5/6)…(9/10) = 2/10 = 1/5, the same k/n as every item.
More Coding Interview Problems questions
- Problem: An LFU cache (capacity 2) evicts the least frequently used key; ties are broken by least recently used. get returns −1 on a miss…
- Edge case: A generator expression is consumed twice. python g = (x x for x in range(4)) print(sum(g), sum(g)) What is printed?
- Problem: Sort students by grade (descending), breaking ties by name (ascending), using two passes of Python's STABLE sort. python s =…
- Problem: Find the length of the SHORTEST subarray with sum ≥ k when values may be negative (monotonic deque over prefix sums). python from…
- Problem: Longest subarray whose max − min ≤ limit, using two monotonic deques. python from collections import deque def longest(a, lim)…
- Problem: Count subarrays whose maximum lies in [L, R] in one pass. python def count(a, L, R): lastbad = lastok = -1; res = 0 for i, x in…