AlgoMaster Logo

Insert Delete GetRandom O(1)

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. List and HashSet

Intuition:

We can use a combination of a list and a set to achieve the operations required by the problem. The list allows us to efficiently access and remove elements with the help of an index, while the set ensures that we don't insert duplicate elements, owing to its unique property. However, removing an element from the middle of the list is an O(n) operation, which doesn't meet the optimal constraint, but it is a stepping stone towards understanding the problem.

Code:

2. HashMap and ArrayList

Intuition:

To achieve O(1) on all operations, we can use a combination of a HashMap to store elements and their indices, and an ArrayList to store the elements. The HashMap gives us O(1) access and removal time when handling key-value pairs, while the ArrayList provides O(1) time for random access. The trick to efficiently remove an element from the list is to swap the element to remove with the last element, then remove the last element. This approach retains the order only up to the end where the swap happens, which is acceptable since we only need getRandom to return any element.

Code: