The Insert Delete GetRandom O(1) interview question is a classic systems-design-lite task. You are building a class that manages a collection of unique integers. The primary constraint is that insertion, deletion, and picking a random element must all happen in average time complexity. This requires a creative combination of data structures to bypass the limitations of standard arrays or hash tables.
This is one of the most popular questions at Apple, Uber, and Google. It tests your ability to evaluate the time complexity of different data structure operations. It evaluates if you can identify that an array is necessary for random access, while a hash map is necessary for search and deletion. It’s a perfect test of Design interview patterns.
This solution uses the Array and Hash Map combination.
Value -> Position.Position -> Value.Suppose we have values {5, 8, 3}.
Array: [5, 8, 3]. Map: {5:0, 8:1, 3:2}.
getRandom(): Pick random index 0, 1, or 2.remove(8):
[5, 3].{5:0, 3:1}. 8 is removed.This problem is all about "The Tradeoff." Arrays are bad at finding elements but great at random access. Maps are great at finding elements but bad at random access. Combining them is a fundamental trick in building efficient Randomized interview pattern 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 | |
| Finding Pairs With a Certain Sum | Medium | Solve |