This is the "Hard" version of the randomized set problem. You must support insert, remove, and getRandom in , but the set can now contain duplicate values. Each instance of a value must have an equal probability of being returned by getRandom().
Companies like Citadel and Peloton ask the Insert Delete GetRandom O(1) - Duplicates allowed coding problem to see if a candidate can handle complex state management. It requires a Hash Table interview pattern where the value maps to a set of indices, making the "Swap and Pop" logic significantly more complex to maintain.
This uses a Hash Map of Sets + Dynamic Array.
Map<Integer, Set<Integer>>: Maps each value to a set of all indices where that value appears in the array.ArrayList<Integer>: Stores the values.val, pick any index from map.get(val). Swap the element at that index with the very last element in the array, update the last element's set in the map to reflect its new index, and then remove the original index from val's set.Array: [10, 10, 20]. Map: {10: {0, 1}, 20: {2}}.
remove(10):
[20, 10, 20].{20: {0}}.[20, 10].{10: {1}}.getRandom. (The array naturally handles this if each instance has its own slot).Practice using "Multimaps" or "Map of Sets." In design problems, adding duplicates usually means transforming a Value -> Data mapping into a Value -> Collection<Data> mapping.
| 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 |