Skip to main content

Insert Delete GetRandom O(1) - Solution & Explanation

MediumArrayHash TableMathDesign26 min readAsked at: Amazon, Microsoft, Apple +35
Practice this problem

Problem Statement

Implement the RandomizedSet class:

  • RandomizedSet() Initializes the RandomizedSet object.
  • bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
  • bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
  • int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.

You must implement the functions of the class such that each function works in average O(1) time complexity.

 

Example 1:

Input
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"]
[[], [1], [2], [2], [], [1], [2], []]
Output
[null, true, false, true, 2, true, false, 2]

Explanation
RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully.
randomizedSet.remove(2); // Returns false as 2 does not exist in the set.
randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly.
randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2].
randomizedSet.insert(2); // 2 was already in the set, so return false.
randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

 

Constraints:

  • -231 <= val <= 231 - 1
  • At most 2 * 105 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

Approach Overview

Problem Overview: Design a data structure that supports insert(val), remove(val), and getRandom() in average O(1) time. The random operation must return each stored element with equal probability.

Approach 1: Divide and Conquer Approach (Array + Hash Map) (Time: O(1), Space: O(n))

The key idea is combining a dynamic array with a hash map. The array stores elements so you can pick a random value in constant time using a random index. The hash map stores value → index so you can locate elements instantly during deletion. When removing a value, swap it with the last element in the array, update the hash map for the swapped value, and then pop the last element. This avoids expensive shifting operations and keeps deletion O(1). Hash lookups and updates provide constant time access, which makes all three operations efficient. This design heavily relies on concepts from Hash Table and Array data structures.

Approach 2: Iterative Approach using Heap Sort (Time: O(log n), Space: O(n))

A less optimal design stores values inside a heap-like structure where insertions and deletions follow heap operations. Insert pushes the element and rebalances the heap in O(log n). Removal searches and restructures the heap afterward. Random selection can be simulated by choosing a random index from the heap array representation, but heap adjustments during updates increase the complexity. While workable, this structure sacrifices the constant-time requirement and mainly demonstrates how iterative heap-based structures manage dynamic collections. Concepts overlap with Design and randomized data structures.

Recommended for interviews: Interviewers expect the array + hash map design. It demonstrates understanding of constant-time hash lookups and how swapping with the last array element avoids costly deletions. Discussing the heap-based or naive structures first shows awareness of tradeoffs, but the hash map + array combination is the standard optimal solution.

Approach 1: Divide and Conquer Approach

This approach breaks down the problem into smaller subproblems. We solve the subproblems recursively and then combine their solutions to solve the original problem. This is useful in problems like merge sort or quicksort.

This C code implements the merge sort algorithm using a divide and conquer approach. It recursively breaks down the array into two halves, sorts them, and then merges the sorted halves.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n)
Space Complexity: O(n)

Try this approach in the editor →

Approach 2: Iterative Approach using Heap Sort

This approach uses a binary heap data structure to sort the elements. Unlike the recursive nature of merge sort, heap sort uses an iterative process to build a max heap and then extracts the maximum element one by one.

This C code sorts an array using heap sort, an iterative algorithm utilizing a binary heap to extract the largest elements and build the sorted array.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n log n)
Space Complexity: O(1)

Try this approach in the editor →

Approach 3: Hash Table + Dynamic List

We define a dynamic list q to store the elements in the set, and a hash table d to store the index of each element in q.

When inserting an element, if the element already exists in the hash table d, return false directly; otherwise, we insert the element into the end of the dynamic list q, and insert the element and its index in q into the hash table d at the same time, and finally return true.

When deleting an element, if the element does not exist in the hash table d, return false directly; otherwise, we obtain the index of the element in the list q from the hash table, then swap the last element q[-1] in the list q with q[i], and then update the index of q[-1] in the hash table to i. Then delete the last element in q, and remove the element from the hash table at the same time, and finally return true.

When getting a random element, we can randomly select an element from the dynamic list q and return it.

Time complexity O(1), space complexity O(n), where n is the number of elements in the set.

Code

Python

Java

C++

Go

TypeScript

Rust

C#

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Divide and Conquer Approach

Time Complexity: O(n log n)
Space Complexity: O(n)

Iterative Approach using Heap Sort

Time Complexity: O(n log n)
Space Complexity: O(1)

Hash Table + Dynamic List—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Divide and Conquer (Array + Hash Map)O(1) average for insert, delete, getRandomO(n)General case when constant-time operations are required
Iterative using Heap SortO(log n) insert/delete, O(1) random accessO(n)When using heap-based structures or learning alternative dynamic storage approaches

Video Solution

Insert Delete GetRandom O(1) - Leetcode 380 - Python • NeetCode • 80,413 views views

Watch 9 more video solutions →

Frequently Asked Questions

How to solve Insert Delete GetRandom O(1)?
Store elements in a list (or dynamic array) and maintain a hash map that maps values to their indices. Insert pushes the value into the array and records its index. Remove swaps the element with the last array element, updates the map, and pops the array. getRandom returns the element at a randomly generated index.
Is Insert Delete GetRandom O(1) easy or hard?
Insert Delete GetRandom O(1) is classified as a Medium difficulty problem. The challenge is recognizing that a single data structure cannot support all operations efficiently, so combining a hash map with an array provides the required constant-time performance.
Insert Delete GetRandom O(1) Python/Java solution
Most Python and Java solutions implement a class that stores an ArrayList or list along with a HashMap or dictionary mapping values to indices. The swap-with-last trick ensures deletions stay O(1), and built-in random number generation returns a random element.
What is the best approach for Insert Delete GetRandom O(1)?
The optimal approach uses a combination of a dynamic array and a hash map. The array enables constant-time random access, while the hash map tracks each value's index for quick lookup and deletion. By swapping the element to delete with the last array element and updating the index in the map, all operations run in average O(1) time.
Is Insert Delete GetRandom O(1) asked at Google/Amazon/Meta?
Insert Delete GetRandom O(1) is a common interview question at large tech companies including Google, Amazon, Meta, and Microsoft. It evaluates your ability to design efficient data structures and combine arrays with hash maps for constant-time operations.
What data structure is used in Insert Delete GetRandom O(1)?
The standard solution uses two structures: a dynamic array for O(1) random access and a hash table that maps each value to its index in the array. This combination allows constant-time insertions, deletions, and random retrieval.
What is the time complexity of Insert Delete GetRandom O(1)?
The optimized data structure achieves average O(1) time for insert, remove, and getRandom operations. Insert appends to the array and records the index in a hash map. Remove swaps the element with the last item before deletion, and getRandom selects a random index from the array.

Ready to solve this problem?

Practice Insert Delete GetRandom O(1) with our built-in code editor and test cases.

Practice on FleetCode