15% off all plans & roadmaps Use code

See plans

Insert Delete GetRandom O(1)

Updated

TL;DR: The set needs insert, remove and random pick to each run in O(1) average time. Keep a dynamic array for random access and a hash map from value to index, then delete by swapping the target with the last element.

Problem

Implement the RandomizedSet class. It stores a set of integers and supports three operations. Each operation must run in average O(1) time.

  • RandomizedSet() creates the object.
  • bool insert(int val) adds val if it is not already in the set. Returns true when it was added and false when it was already present.
  • bool remove(int val) removes val if it is in the set. Returns true when it was removed and false when it was not present.
  • int getRandom() returns one element of the current set. At least one element exists when this is called. Each element must have the same probability of being returned.

Example 1

Input: ["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] and [[], [1], [2], [2], [], [1], [2], []]
Output: [null, true, false, true, 2, true, false, 2]
Explanation: insert(1) returns true. remove(2) returns false because 2 is absent. insert(2) returns true, so the set holds [1, 2]. getRandom() returns either 1 or 2. remove(1) returns true, leaving [2]. insert(2) returns false because 2 is already present. getRandom() always returns 2.

Constraints

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

Constraints that matter

  • Values span the full 32-bit signed range, so you cannot use a boolean array indexed by value. You need a hash map keyed by value.
  • Up to 2 * 10^5 calls means an O(n) step per call can reach about 4 * 10^10 steps in the worst case. That is too slow.
  • At least one element exists when getRandom runs, so the random index always has a non-empty range.
  • Every element needs the same probability, so the random pick must be uniform over the stored slots.

View on LeetCode

Hints

Hint 1

This is a design problem.

Hint 2

Store the values in one list.

Solution

Intuition

This is a design problem. No single standard structure meets all three bounds, so you combine two structures. Pick each one to cover the other's weakness. This is the combined data structure design pattern.

Picture a row of numbered lockers and a clipboard listing each item's locker number. The row is nums, the clipboard is pos, and emptying a middle locker means moving the last item into it.

Start with what each operation needs. getRandom needs indexed access to any stored value in O(1). remove needs to find where a value lives in O(1). An array gives the first property and a hash map gives the second. A hash set alone fails getRandom, and an array alone fails remove.

The set has no order, so order does not need protecting. When you delete from the middle, you can move the last value into the hole and drop the last slot. This keeps the array dense, so every index from 0 to n - 1 is valid. A uniform random index then gives a uniform random value.

The map must follow the moved value so later lookups stay correct.

Watch the pattern animation

Worked example

Input: RandomizedSet, insert(10), insert(20), remove(10), getRandom()
Output: [null, true, true, true, 20]
Explanation: The first two inserts add 10 and 20, so the set holds both values. The remove call deletes 10, which leaves only 20. With one element left, getRandom must return 20.

Approach 1: Brute force with a plain list

Store the values in one list. insert scans the whole list to check for a duplicate, then appends. remove scans for the value, then shifts every later element one slot left. getRandom picks a random index, which is O(1) on a list.

What's slow: insert and remove both scan the list. A scan can touch all n values, and a remove also shifts up to n - 1 values. The work per call grows with the set size, so the total cost grows with n squared over the calls.

Steps

  1. Create an empty list in the constructor.
  2. In insert, return false if val is already in the list.
  3. Otherwise append val to the list and return true.
  4. In remove, search the list for val. Return false if it is missing.
  5. If found, delete that slot so later values shift left, and return true.
  6. In getRandom, pick a uniform random index and return the value stored there.

Dry run

On the example, insert(10) scans an empty list, finds nothing, and appends. The list is [10]. insert(20) scans [10], finds no 20, and appends, giving [10, 20]. remove(10) scans, finds 10 at index 0, and shifts 20 into slot 0, giving [20]. getRandom() picks index 0, which returns 20.

Complexity

TimeO(n) for insert and remove, O(1) for getRandom
SpaceO(n)

Let n be the number of stored values. insert checks every value in the worst case before appending, so it costs O(n). remove searches up to n values and then shifts up to n - 1 values, so it also costs O(n). getRandom reads one index and does not depend on n. The list holds n values, so space is O(n).

PythonTested in our runner

from typing import List, Optional
import random

class RandomizedSet:
    def __init__(self):
        self.items = []

    def insert(self, val: int) -> bool:
        if val in self.items:
            return False
        self.items.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.items:
            return False
        self.items.remove(val)
        return True

    def getRandom(self) -> int:
        return random.choice(self.items)

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: List plus hash map, swap and popOptimalDesign (General/Specific)

What's slow: the previous approach finds values by scanning the list. A scan costs O(n), and removing from the middle also shifts values.

The insight that fixes it: a set has no order, so a removal only has to fill one hole. Move the last value into the hole, then drop the last slot. A hash map from value to its index finds the hole in O(1). It also answers the duplicate check in O(1). The map must be updated for the value that moved.

Why it is correct. The two structures always agree: nums holds exactly the stored values, and pos[v] is the index where v sits in nums. Insert appends and records the new index, so the invariant holds. Remove changes only two entries: the hole gets the last value and that value's index is updated. Because the set has no order, nothing else needs to move, so the invariant survives every operation.

Steps

  1. In the constructor, create an empty list nums and an empty map pos from value to index.
  2. In insert, return false if val is a key in pos.
  3. Otherwise set pos[val] to the current length of nums, append val to nums, and return true.
  4. In remove, return false if val is not a key in pos.
  5. Otherwise read idx = pos[val] and last = nums[-1].
  6. Write last into nums[idx], set pos[last] = idx, pop the last slot of nums, and delete pos[val].
  7. In getRandom, pick a uniform index in [0, len(nums) - 1] and return that value.

Dry run

Trace the example. Step 1 inserts 10 at index 0. Step 2 inserts 20 at index 1. Step 3 is the removal that matters.

For remove(10), idx is 0 and last is 20. Writing 20 into slot 0 gives [20, 20]. Setting pos[20] = 0 keeps the map correct. Popping the last slot leaves [20], and deleting key 10 leaves {20: 0}.

Step 4 picks index 0, which returns 20.

StepCallnumsposReturns
0start[]{}-
1insert(10)[10]{10: 0}true
2insert(20)[10, 20]{10: 0, 20: 1}true
3remove(10)[20]{20: 0}true
4getRandom()[20]{20: 0}20

Complexity

TimeO(1) average per operation
SpaceO(n)

Let n be the number of stored values. insert does one map lookup, one map write and one append, so each costs O(1) on average. remove does one map lookup, two writes to nums and pos, one pop and one map delete, all O(1) on average. getRandom generates one random index and reads one slot. The list and the map each hold at most n entries, so space is O(n).

PythonTested in our runner

from typing import List, Optional
import random

class RandomizedSet:
    def __init__(self):
        self.nums = []
        self.pos = {}

    def insert(self, val: int) -> bool:
        if val in self.pos:
            return False
        self.pos[val] = len(self.nums)
        self.nums.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.pos:
            return False
        idx = self.pos[val]
        last = self.nums[-1]
        # Move the last value into the hole, then drop the last slot.
        self.nums[idx] = last
        self.pos[last] = idx
        self.nums.pop()
        del self.pos[val]
        return True

    def getRandom(self) -> int:
        return random.choice(self.nums)

Common mistakes

  • Deleting pos[val] before writing pos[last] = idx. When val is the last element, the later write recreates the key for a removed value, so a future insert of that value returns false. Write the moved index first, then delete.
  • Forgetting to update pos[last] after the swap. The moved value keeps its old index, so the next remove of that value writes into the wrong slot and corrupts the set.
  • Calling nums.remove(val) or list.remove on the value in the middle. That scans and shifts, which is O(n) per call. Swap the target with the last slot instead.
  • In Java, writing nums.remove(last) with an int argument removes by index, not by value. Use nums.remove(nums.size() - 1) to pop the last slot.
  • Checking val in self.nums or nums.contains(val) for the duplicate test. That is a scan. The map check val in pos answers the same question in O(1).
  • Building getRandom from the map, for example by iterating the dictionary or calling random.choice on its keys. That is O(n) and it removes the uniform index over the dense array. Sample from nums instead.

Edge cases

  • Remove the only element. The target and the last slot are the same, so the swap writes the value onto itself. The set becomes empty and remove returns true.
  • Insert a value that is already present. insert returns false, and the list and map do not change.
  • Remove a value that was never inserted. remove returns false, and nothing changes.
  • Insert, remove, then insert the same value again. The second insert returns true, because the map entry was deleted.
  • Use the extremes -2^31 and 2^31 - 1, plus negative values. Each fits in a 32-bit int, so no overflow happens in any of the six languages.
  • Run 2 * 10^5 mixed calls. After each call, the map size must equal the list length, and every stored value must map to its exact index.

Follow-ups interviewers ask

What if the set may hold duplicates?
Map each value to a collection of its indices instead of one index. insert appends the value and records the new index. remove picks any index for that value, swaps it with the last slot, and updates the index collection of the moved value. Each step stays O(1) on average. You must handle the case where the removed value and the moved value are the same.
What if removals must keep the insertion order?
Swap and pop moves the last value into the hole, so the order breaks. A doubly linked list keeps order with O(1) removal, but it cannot reach a random position in O(1). An order-statistic tree supports ordered removal and a random pick in O(log n) each, so you give up the O(1) bound.
What if the values do not fit in memory?
The list and the map both hold every value, so a truly huge set needs external storage. You can keep the values in a disk-based store and keep only a partial index in memory. If you only need one random sample from a stream and never remove, reservoir sampling keeps one value in O(1) space.

Insert Delete GetRandom O(1) FAQ

What is the time complexity of Insert Delete GetRandom O(1)?

Each of the three operations runs in O(1) average time. Insert and remove each do a fixed number of hash map operations plus one list append or swap. getRandom reads one random index, so the total space is O(n) for n stored values.

Why use a hash map with an array for Insert Delete GetRandom O(1)?

The array gives O(1) random access, which getRandom needs. The hash map gives O(1) lookup of a value's position, which remove needs. A hash set alone cannot pick a random element quickly, and an array alone cannot find a value quickly.

Can Insert Delete GetRandom O(1) be solved in O(1) extra space?

No. The set must store all n values, so the storage is O(n). The map is the extra structure that makes remove O(1), and dropping it brings back the O(n) scan in remove.

Why are the bounds only average O(1)?

Hash map operations are O(1) on average. Under adversarial collisions, a lookup can degrade to O(n). The problem asks for average bounds, so a standard hash table meets the requirement.

What is the Python gotcha with this problem?

list.remove(val) looks easy, but it scans the list and shifts the values after it, which is O(n). Keep a dictionary from value to index and do the swap by hand. random.choice on a list is O(1), so getRandom stays fast.

Asked at

See which companies ask this — Pro

Practise it