Classic problem, I'd seen it before, but the O(1) getRandom part still takes a second to click.
Combine a hash map for O(1) insert/delete with a dynamic array for O(1) random access. When deleting, swap the target element with the last element in the array, update the hash map, then pop the last element. This maintains O(1) average time for all operations.
Pro tip: Mention that this design is used in real-world systems like load balancers and caches for random eviction, and discuss how it handles duplicates if allowed. Also, clarify that getRandom returns each element with equal probability.
Ask if duplicates are allowed, if getRandom should return each element with equal probability, and if the data structure needs to handle other operations. Confirm that average O(1) is acceptable.
Select a hash map (dictionary) to store value-to-index mappings for O(1) lookup, and a dynamic array (list) to store elements for O(1) random access.
Append the new element to the array and record its index in the hash map. If duplicates are allowed, the hash map should map value to a set of indices.
To delete a value, retrieve its index from the hash map. Swap it with the last element in the array, update the hash map for the swapped element, then remove the last element from the array and the value from the hash map.
Generate a random index between 0 and array length - 1 and return the element at that index. This gives each element an equal probability.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.