# 380. Insert Delete GetRandom O(1)

![](/files/P5fyp2zED19aRqZCbUdA)

![](/files/FTbb1I6t2VMWATUkUEu1)

time: all O(1)

space: O(1\~n)

```java
class RandomizedSet {

    private List<Integer> nums;
    private Map<Integer, Integer> numToIndex; // map<num, num's index>
    private Random rand;
    
    public RandomizedSet() {
        nums = new ArrayList<>();
        numToIndex = new HashMap<>();
        rand = new Random();
    }
    
    public boolean insert(int val) {
        //if insert ok return true, or false
        if (numToIndex.containsKey(val)) {
            return false;
        }
        numToIndex.put(val, nums.size()); // 
        nums.add(val);
        return true;
    }
    
    public boolean remove(int val) {
        //if remove ok return true, or false
        if (!numToIndex.containsKey(val)) {
            return false;
        }
        // how to not shift each index? 
        // if not delete last num, replace delete num's position by last num, then delete last num
        // deleteNum,xxxxx  lastNum
        int deleteNumIndex = numToIndex.get(val);
        int lastNum = nums.get(nums.size()-1);
        if (deleteNumIndex != nums.size()-1) {
            nums.set(deleteNumIndex, lastNum);
            numToIndex.put(lastNum,deleteNumIndex);
        }
        nums.remove(nums.size()-1);
        numToIndex.remove(val);
        return true;
    }
    
    public int getRandom() {
        // guaranteed that at least one element exists when this method is called
        return nums.get(rand.nextInt(nums.size()));
    }
}

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet obj = new RandomizedSet();
 * boolean param_1 = obj.insert(val);
 * boolean param_2 = obj.remove(val);
 * int param_3 = obj.getRandom();
 */j
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/design/380.-insert-delete-getrandom-o-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
