Insert Delete GetRandom o(1) Solution

In this problem, We have to design a data structure that supports Insert, Delete, and GetRandom in average O(1) time.

OR

Design a data structure that supports insert, delete, and getRandom in constant time O(1).

insert(value): Inserts an item value to the set if it’s not present.

remove(value): Removes an item value 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.

For Example –

insert delete getrandom O(1) solution

In this problem, we have to implement insert, remove and get random operations in O(1). Let’s first think which data structure should we use to implement all of the three methods in O(1).

Programming Video Tutorials

Let’s consider few data structures and see whether we able to solve this problem using these data structures.

i) By using HashMap or HashSet

The first choice comes to our mind is to use HashMap or HashSet. By using HashMap or HashSet we can insert and remove in O(1) but what about getRandom() method. To implement getRandom() we have to choose random index and return the element present at that index, which is not possible using HashMap or HashSet.

ii) By using ArrayList

What about ArrayList, Can we solve this problem using ArrayList? By using ArrayList we can implement insert() and getRandom() method in O(1) but what about remove() method.

Now, we are clear that by using these data structures alone, we won’t be able to implement all the three operations in O(1). To solve this problem we have to use both HashMap and ArrayList.

Programming Question on Binary Tree

Insert Delete GetRandom O(1) using HashMap and ArrayList – Java Code

We can solve this problem by using HashMap and ArrayList. The idea here is to first insert each element in an ArrayList and in HashMap we put the element and its index (Element index which is present in ArrayList).

Insert() Method Implementation

If element which we are going to insert is already present in a Map then we simply return false. Else we first add this element in an ArrayList and then we put the element and its index in a Map.

Remove() Method

If an element is not present in a Map then simply return false. Else first get the index value of this element from a map. Swap the value present at that index with the last element of the ArrayList. Then delete the last element and update the swapped element’s new index in a Map.

GetRandom() Method

We can use the Random class getInt() method, in which we pass the list size.

Let’s write it’s java code.

Insert delete getrandom O(1) video tutorial

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.