Design dynamic weighted random sampling with updates
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's ability to design and analyze dynamic data structures that support weighted random sampling with inserts and deletes, testing skills in algorithm design, complexity analysis, and randomized sampling under large numeric constraints.
Constraints
- 1 <= len(operations) <= 100000
- 1 <= weight <= 10^9 for insert operations
- IDs are integers and may be sparse or large in magnitude
- The total active weight can exceed 32-bit integer range
- Insert on an existing ID must be treated as a weight update
- Delete on a missing ID is a no-op
Examples
Input: [("insert", 10, 4), ("insert", 20, 6), ("sample", 1), ("sample", 4), ("sample", 5), ("sample", 10)]
Expected Output: [10, 10, 20, 20]
Explanation: In increasing ID order, 10 owns [1,4] and 20 owns [5,10].
Input: [("insert", 5, 3), ("insert", 2, 2), ("sample", 4), ("insert", 5, 1), ("sample", 2), ("delete", 2), ("sample", 1), ("delete", 5), ("sample", 1)]
Expected Output: [5, 2, 5, -1]
Explanation: Insert on existing ID updates its weight. After all deletions, sampling from an empty set returns -1.
Hints
- Compress item IDs into fixed indices, then store current weights in a Fenwick tree or segment tree.
- A sample query is equivalent to finding the first index whose prefix-sum weight is at least r.