Insert Delete GetRandom O(1)

MediumHash Map + Array · Design🧩 Data Structure DesignLeetCode #380 ↗Updated

Problem

Design a class RandomizedSet holding distinct integers. insert(val) adds val if absent and remove(val) deletes it if present (each returns whether the set changed). getRandom() returns a current element, each with equal probability. All three operations must run in average O(1) time.
Inputinsert(1) remove(2) insert(2)Outputtrue, false, true
InputgetRandom() remove(1) insert(2)Output1 or 2, true, false

-231 ≤ val ≤ 231-1  ·  ≤ 2·105 calls  ·  getRandom only on a non-empty set  ·  each op average O(1)

Try it yourself

Java
class RandomizedSet {
    public boolean insert(int val) {
        
    }

    public boolean remove(int val) {
        
    }

    public int getRandom() {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
A hash set gives O(1) lookup but no O(1) random access; an array gives random access but slow deletes. Combine them, and delete from the array by swapping the victim with the last element and popping the tail — order doesn't matter for a set.
PatternData Structure Design

Instinct Implement a class whose methods must all hit a time bound (often O(1)) - write each method's target cost, then glue a hash map to a structure that keeps order.

Memory hack Finder plus keeper - a hash map finds it fast, a list/heap/array keeps the order, and every method updates both.

Open the Data Structure Design guide →

Approaches

Brute ForceArrayList Only

Time O(n) insert/remove, O(1) getRandomSpace O(n)

Store the elements in a list. Duplicate checks and deletions scan the list, while getRandom picks a uniform random index — every element occupies exactly one slot, so each is equally likely.

Java
class RandomizedSet {
    private final List<Integer> list = new ArrayList<>();
    private final Random rand = new Random();

    public boolean insert(int val) {
        if (list.contains(val)) return false;   // O(n) scan
        list.add(val);
        return true;
    }

    public boolean remove(int val) {
        return list.remove((Integer) val);      // O(n) scan + shift
    }

    public int getRandom() {
        return list.get(rand.nextInt(list.size()));
    }
}

Random access is free, but membership checks make insert and remove linear.

At a glance

LevelApproachTimeSpace
Brute ForceArrayList OnlyO(n) insert/remove, O(1) getRandomO(n)
BetterArrayList + HashSetO(1) insert/getRandom, O(n) removeO(n)
OptimalHashMap (val → index) + ArrayList, Swap with LastO(1) average all opsO(n)
Common pitfalls
  • list.remove(val) with an int removes by index; cast to Integer.
  • Forgetting to update the moved element's index in the map after the swap.
  • Removing the last element itself — re-inserting it into the map resurrects it.
Interview tips
  • Name what each structure buys: map = O(1) lookup, array = O(1) random index.
  • Explain why swap-with-last is legal: a set has no order to preserve.
  • Follow-up with duplicates (LC 381): map value → set of indices.
Pattern
Hash map + dense array → O(1) lookup, delete and uniform random sampling together.
My notes saved in this browser