Random Hash DS
Implement a set-like data structure with three methods:
Insert an element
Remove an element (by value); and
Return an element chosen uniformly at random
e.g. After inserting 1, 3, 7, 2 and 9 in that order, we could remove 7, and the random number would be one of {1, 3, 2 or 9} each with 25% probability.
Brain storm:
Binary tree: Constant space with logN insertions and deletions, and O(N) random returns.
Hash table
O(1) inserts and deletes.
O(N) random
Working off this idea, once thing we can do is use a secondary hash structure, like an vector (which support O(1) removal and deletions by index).
Essentially we use the secondary vector as a container that reverses the order of our map structure. Our map is
<value, index>
and our vector is<index, value>
. Using these two details, we can find both the value or index, in O(1) time. Removals are just swapping and removing things from the end, and modifying our map to accommodate that.
Last updated