Skip to main content
Back to problems
#380
Medium Algorithms

Insert delete getrandom o1

Array Hash Table Math Design Randomized
55.3% acceptance
Jan 12, 2026
9923
696
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.

Solution

Rust
Time O(2^n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;

struct RandomizedSet {
  map: HashMap<i32, usize>,
  vec: Vec<i32>,
}

impl RandomizedSet {
  fn new() -> Self {
    RandomizedSet {
      map: HashMap::new(),
      vec: Vec::new(),
    }
  }
  
  fn insert(&mut self, val: i32) -> bool {
    use std::collections::hash_map::Entry;
    match self.map.entry(val) {
      Entry::Occupied(_) => false,
      Entry::Vacant(e) => {
        e.insert(self.vec.len());
        self.vec.push(val);
        true
      }
    }
  }
  
  fn remove(&mut self, val: i32) -> bool {
    if let Some(&idx) = self.map.get(&val) {
      let last_idx = self.vec.len() - 1;
      if idx != last_idx {
        let last_val = self.vec[last_idx];
        self.vec[idx] = last_val;
        self.map.insert(last_val, idx);
      }
      self.vec.pop();
      self.map.remove(&val);
      true
    } else {
      false
    }
  }
  
  fn get_random(&self) -> i32 {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hash, Hasher};
    
    let state = RandomState::new();
    let mut hasher = state.build_hasher();
    self.vec.len().hash(&mut hasher);
    let hash = hasher.finish();
    let idx = (hash as usize) % self.vec.len();
    self.vec[idx]
  }
}