Insert Delete GetRandom O(1)
LeetCode Problem #380 (Medium)
Last updated
Was this helpful?
LeetCode Problem #380 (Medium)
Last updated
Was this helpful?
Design a data structure that supports all following operations in average O(1) time.
insert(val)
: Inserts an item val to the set if not already present.
remove(val)
: Removes an item val from the set if present.
getRandom
: Returns a random element from current set of elements. Each element must have the same probability of being returned.
O(1) time complexity is also referred to as constant time. If an operation is said to be performed in constant time, it means that irrespective of the size of the data set within which the operation is performed, the time taken to accomplish the task will be constant.
To illustrate, let us consider an array of size 5. To find an element in this array, we assume that it takes 1 second. If we double the size of the array to contain 10 elements and if we want to search for an element now, it would take the same 1 second to find the element, if this operation is designed to execute in constant time.
As shown in the chart below, O(1) is the most ideal time complexity that a particular operation could have, since the increase in the number of elements in a data set will not affect the performance of the operation.
Initialize a vector to store all of the elements.
Initialize a map to track the key and value of every element.
Check the array to see if the value to be inserted exists or not.
If the value does not exist, using the emplace() method, insert the value and its position in the map only if it is unique.
Add the value to the array.
Check the array to see if the value to be removed exists or not.
If the value exists, obtain the index of the value from the map and store it in a variable.
Move the element to be removed to the back of the array and remove it from the array.
Change the index value in the map to the correct value and remove the value from the map.
Calculate the index of the element to return by performing taking a random number and performing modulus with the size of the array.(This is to prevent the index from going out of bounds.)
Access the element at the calculated index from the vector.