Weighted Random Sampling Data Structures
Asked of: Software Engineer
Last updated
What's being tested
You must design a dynamic data structure that supports insert, delete, and getRandom where getRandom returns items proportional to their weight. Interviewers probe your knowledge of hybrid array+map layouts, prefix-sum indexing, update/search complexity tradeoffs, and numeric robustness under updates.
Patterns & templates
- hashmap+array hybrid — store items in an array for indexable operations and a
hashmapfor index lookup; swap-with-last for O(1) delete. - prefix-sum array with binary search — maintain cumulative weights; sample by generating
r in [0,total)and binary-searchO(log n)per sample. - Fenwick tree (Binary Indexed Tree) — supports point updates and prefix-sum queries in O(log n); use for frequent weight changes.
- Alias method — preprocess in O(n) to enable O(1) sampling; good when samples >> updates but costly for frequent inserts/deletes.
- For mostly-read, infrequent-write workloads: rebuild prefix/alias lazily (batch updates) to amortize costs.
- Track total weight explicitly; for sampling use uniform
rand()scaled to total to avoid bias. - Use
int64or double carefully; avoid cumulative rounding by using integer weights when possible, or renormalize periodically. - Complexity shorthand:
insert/deleteamortized O(1) with array+map, sampling O(log n) with Fenwick/prefix, O(1) with alias after rebuild.
Common pitfalls
Pitfall: Treating floating cumulative sums as exact — leads to off-by-one or bias; prefer integer weights or careful eps handling.
Pitfall: Forgetting to update both array and tree/map on swap-delete — leaves stale indices and corrupts sampling.
Pitfall: Choosing alias method without asking update frequency — great for static weights but expensive for dynamic workloads.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Practice questions
Related concepts
- Randomized Sampling AlgorithmsCoding & Algorithms
- Probability, Weighted Sampling, And Random WalksStatistics & Math
- Top-K Selection, Heaps, And RankingCoding & Algorithms
- Mutable Data Structures And O(1) DesignCoding & Algorithms
- Heaps, Top-K, And Streaming SelectionCoding & Algorithms
- Top-K, Heaps, Quickselect, And Frequency AnalysisCoding & Algorithms