I started with a hashmap and felt pretty good about it until they asked about getRandom.
Use a dynamic array to store all elements (including duplicates) and a hash map from value to a set of indices in the array. For add, append the value and add its index to the map; for remove, swap the target element with the last element, update the map for both, and pop the last element; for getRandom, pick a random index from the array. This ensures average O(1) time for all operations and correct probability proportional to frequency.
Pro tip: Mention that using a set of indices per value allows O(1) removal even with duplicates, and discuss the trade-off between using a set versus a list for indices (e.g., set gives O(1) removal but higher constant factors).
Confirm that duplicates are allowed, getRandom must be weighted by frequency, and all operations should be average O(1). Ask about memory constraints and whether values can be any type.
Propose a dynamic array (list) to store all elements in order, and a hash map mapping each value to a set of indices where it appears in the array.
For add: append to array, add index to map. For remove: get an index from the map, swap with last element, update map for swapped element, remove last element, and remove index from map.
Generate a random integer between 0 and array length - 1 and return the element at that index. This gives each occurrence equal probability, hence weighted by frequency.
Discuss average O(1) time for all operations, handle edge cases like removing the last element, removing when only one occurrence, and empty structure.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.