Design a data structure that supports following operations in Θ(1) time.
insert(x): Inserts an item x to the data structure if not already present.
remove(x): Removes an item x from the data structure if present.
search(x): Searches an item x in the data structure.
getRandom(): Returns a random element from current set of elements
We can use hashing to support first 3 operations in Θ(1) time. How to do the 4th operation? The idea is to use a resizable array (ArrayList in Java, vector in C) together with hashing. Resizable arrays support insert in Θ(1) amortized time complexity. To implement getRandom(), we can simply pick a random number from 0 to size-1 (size is number of current elements) and return the element at that index. The hash map stores array values as keys and array indexes as values.
Following are detailed operations.
1) Check if x is already present by doing a hash map lookup.
2) If not present, then insert it at the end of the array.
3) Add in hash table also, x is added as key and last array index as index.
1) Check if x is present by doing a hash map lookup.
2) If present, then find its index and remove it from hash map.
3) Swap the last element with this element in array and remove the last element.
Swapping is done because the last element can be removed in O(1) time.
4) Update index of last element in hash map.
1) Generate a random number from 0 to last index.
2) Return the array element at the randomly generated index.
Do a lookup for x in hash map.
Below is implementation of the data structure.
2 3 40
This article is contributed by Manish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Efficiently design Insert, Delete and Median queries on a set
- Treap | Set 2 (Implementation of Search, Insert and Delete)
- Design a data structure for LRU Cache
- Design an efficient data structure for given operations
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Queries to insert, delete one occurrence of a number and print the least and most frequent element
- 2-3 Trees | (Search and Insert)
- Trie | (Insert and Search)
- K Dimensional Tree | Set 1 (Search and Insert)
- Binary Search Tree | Set 2 (Delete)
- Design data structures and algorithms for in-memory file system
- Gap Buffer Data Structure
- Design the Data Structures(classes and objects)for a generic deck of cards
- Tango Tree Data Structure
Improved By : SwapnilShukla1