Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #381: Insert Delete GetRandom O(1) - Duplicates allowed

In this guide, we solve Leetcode #381 Insert Delete GetRandom O(1) - Duplicates allowed in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Design, Array, Hash Table, Math, Randomized

Intuition

Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.

By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.

Approach

Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.

This keeps the solution linear while remaining easy to explain in an interview setting.

Steps:

  • Initialize a hash map for seen items or counts.
  • Iterate through the input, querying/updating the map.
  • Return the first valid result or the final computed value.

Example

Input ["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] [[], [1], [1], [2], [], [1], []] Output [null, true, false, true, 2, true, 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.

Python Solution

class RandomizedCollection: def __init__(self): """ Initialize your data structure here. """ self.m = {} self.l = [] def insert(self, val: int) -> bool: """ Inserts a value to the collection. Returns true if the collection did not already contain the specified element. """ idx_set = self.m.get(val, set()) idx_set.add(len(self.l)) self.m[val] = idx_set self.l.append(val) return len(idx_set) == 1 def remove(self, val: int) -> bool: """ Removes a value from the collection. Returns true if the collection contained the specified element. """ if val not in self.m: return False idx_set = self.m[val] idx = list(idx_set)[0] last_idx = len(self.l) - 1 self.l[idx] = self.l[last_idx] idx_set.remove(idx) last_idx_set = self.m[self.l[last_idx]] if last_idx in last_idx_set: last_idx_set.remove(last_idx) if idx < last_idx: last_idx_set.add(idx) if not idx_set: self.m.pop(val) self.l.pop() return True def getRandom(self) -> int: """ Get a random element from the collection. """ return -1 if len(self.l) == 0 else random.choice(self.l) # Your RandomizedCollection object will be instantiated and called as such: # obj = RandomizedCollection() # param_1 = obj.insert(val) # param_2 = obj.remove(val) # param_3 = obj.getRandom()

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy