The Insert Delete GetRandom O(1) - Duplicates allowed interview question is a high-level data structure design challenge. You need to implement a class that stores integers and allows for duplicates. The structure must support insert, remove, and getRandom (which picks an element with probability proportional to its frequency) all in constant average time.
Companies like Meta, Amazon, and Uber ask the Duplicates allowed coding problem to see if a candidate can handle complex updates in a multi-mapped environment. It tests your proficiency with Hash Table interview patterns and your ability to manage pointers/indices within a dynamic array. It’s a rigorous evaluation of your understanding of amortized time complexity and uniform probability distribution.
This problem uses a Hash Map of Indices + Dynamic Array pattern.
getRandom remains and uniform.Value -> Set of Indices where that value appears in the array.Current elements: [1, 1, 2]. Array: [1, 1, 2], Map: {1: {0, 1}, 2: {2}}.
insert(1): Array becomes [1, 1, 2, 1], Map: {1: {0, 1, 3}, 2: {2}}.remove(2):
[1, 1, 1, 2].{0, 1, 2}, 2 is popped.getRandom(): Any index from 0 to 2 is picked with 1/3 probability. 1 has a 2/3 chance, 2 has a 0 chance (removed).Focus on the Probability requirement. Uniform probability over elements means every slot in the storage array must be equally likely to be picked. If a value appears twice, it should occupy two slots.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Insert Delete GetRandom O(1) - Duplicates allowed | Hard | Solve | |
| Insert Delete GetRandom O(1) | Medium | Solve | |
| Insert Delete GetRandom O(1) | Medium | Solve | |
| Shuffle an Array | Medium | Solve | |
| Random Pick with Blacklist | Hard | Solve |