Insert, delete and get random in O(1) with duplicates
Design a collection of integers that allows duplicates and supports, each in average O(1) time:
-
insert(val): add one copy ofval; return whethervalwas absent before. -
remove(val): remove one copy ofvalif present; return whether anything was removed. -
get_random(): return a random element, where each value's chance is proportional to how many copies of it the collection holds.
Explain the array-plus-index-map layout and how you remove from the middle of the array in constant time.
No answer yet. Write the first one; the best answer gets endorsed.
