Insert Delete GetRandom O(1) in Python

The Insert Delete GetRandom O(1) problem requires designing a data structure that supports three operations in average O(1) time: inserting elements, removing elements, and returning a random element with equal probability.

Problem Requirements

  • insert(val) − Insert an item val to the set if not already present

  • remove(val) − Remove an item val from the set if it exists

  • getRandom() − Return a random element with equal probability for all elements

Solution Approach

We use two data structures to achieve O(1) operations:

  • Dictionary (present) − Maps values to their indices in the array for O(1) lookup

  • List (elements) − Stores actual values for O(1) random access

Key Algorithm Steps

  • Insert: Add to end of list and update dictionary

  • Remove: Swap element with last element, then remove last element

  • GetRandom: Use random.choice() on the elements list

Implementation

import random

class RandomizedSet:
    def __init__(self):
        self.present = {}  # Maps value to index
        self.elements = []  # Stores actual values
    
    def insert(self, val):
        if val in self.present:
            return False
        
        # Add to end of list and update dictionary
        self.elements.append(val)
        self.present[val] = len(self.elements) - 1
        return True
    
    def remove(self, val):
        if val not in self.present:
            return False
        
        # Get index of element to remove
        index = self.present[val]
        last_element = self.elements[-1]
        
        # Move last element to the position of element to remove
        self.elements[index] = last_element
        self.present[last_element] = index
        
        # Remove last element and update dictionary
        self.elements.pop()
        del self.present[val]
        return True
    
    def getRandom(self):
        return random.choice(self.elements)

# Example usage
randomized_set = RandomizedSet()

print(randomized_set.insert(1))    # True - inserted 1
print(randomized_set.remove(2))    # False - 2 not present
print(randomized_set.insert(2))    # True - inserted 2
print(randomized_set.getRandom())  # Either 1 or 2
print(randomized_set.remove(1))    # True - removed 1
print(randomized_set.insert(2))    # False - 2 already present
print(randomized_set.getRandom())  # 2 (only element left)
True
False
True
1
True
False
2

Time Complexity Analysis

Operation Time Complexity Explanation
insert() O(1) Append to list and dictionary update
remove() O(1) Swap with last element, then pop
getRandom() O(1) Random access to list element

How Remove Works

The key insight for O(1) removal is swapping the element to be removed with the last element, then removing the last element. This avoids shifting all subsequent elements.

Before removing 2: 1 2 3 4 After removing 2: 1 4 3 Swap element 2 with last element (4), then remove the last position

Conclusion

This solution achieves O(1) average time complexity for all operations by combining a dictionary for fast lookups with a list for random access. The key insight is using the swap-with-last technique for efficient removal.

Updated on: 2026-03-25T08:19:17+05:30

624 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements