Design a data structure that has O(1) add, search, remove,

The key here is to use an Array and a HashMap. The array stores the element while the hashMap stores the element as the key and the index in the Array as the value.

Add: Simply add to the end of the array, also add corresponding entries in the hashmap.
Search: Simple search on the Hashmap.
Remove: Remove from the hashMap, swap the index with the last index of the array, then remove the element from the array, update the swapped element in the hashmap.
getRandom: Generate a random index and access the array.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s