The Insert Delete GetRandom O(1) interview question asks you to design a data structure that supports three operations in constant average time:
insert(val): Inserts an item to the set if not already present.remove(val): Removes an item from the set if present.getRandom(): Returns a random element from the set with equal probability.This is a flagship question for Design interview patterns. Companies like Google, LinkedIn, and Salesforce ask this to see if you can combine multiple data structures to cover each other's weaknesses. A Hash Map is great for insert/delete but can't do getRandom in . An Array is great for getRandom but for deletion. The "Hard" part is making them work together.
This problem follows the Hash Map + Dynamic Array pattern.
Value -> Index in Array. This allows lookups to find where a value is in the array.insert(10): Array = [10], Map = {10: 0}.insert(20): Array = [10, 20], Map = {10: 0, 20: 1}.remove(10):
[20, 20].{20: 0}.[20].getRandom(): Generate random index 0. Return 20.list.remove(value) in Java or Python, which involves a linear search. You must use the map to find the index and the "swap with last" trick.Master the "Swap and Pop" technique. It is the only way to delete from an array in while maintaining a contiguous structure. This is a vital Array interview pattern for high-performance data structures.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Insert Delete GetRandom O(1) | Medium | Solve | |
| Insert Delete GetRandom O(1) - Duplicates allowed | Hard | Solve | |
| Insert Delete GetRandom O(1) - Duplicates allowed | Hard | Solve | |
| Shuffle an Array | Medium | Solve | |
| Line Reflection | Medium | Solve |