Combine a hash map and a dynamic array to achieve O(1) average time for insert, delete, and getRandom. The hash map stores value-to-index mappings, while the array stores the elements; deletion swaps the target with the last element and pops, updating the map accordingly.
Pro tip: Mention that this design is exactly what powers features like random ad selection or shuffle bags in games, showing you understand real-world applications. Also, clarify that O(1) is average-case due to hash collisions, and discuss how you'd handle duplicates if the problem requires it.
Ask whether duplicates are allowed, whether the data structure needs to support other operations, and confirm that average O(1) is acceptable. This shows you think about edge cases before coding.
Select a hash map for O(1) lookups and a dynamic array for O(1) random access. Explain that the map will store value-to-index mappings, and the array will store the actual elements.
For insert, append to the array and add the index to the map. For getRandom, generate a random index and return the array element at that index.
To delete a value, retrieve its index from the map, swap it with the last element in the array, update the map for the swapped element, then pop the last element and remove the deleted value from the map.
Confirm that all operations are O(1) average time. Discuss handling of duplicates (e.g., using a set of indices per value) and empty structure edge cases.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.