Problem solution · Python

Insert Delete Getrandom O1

Insert Delete Getrandom O1: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Direct simulation
Source
Kamyu LeetCode Solutions
Length
57 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For Insert Delete Getrandom O1, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 57 lines of Python from the credited upstream file insert-delete-getrandom-o1.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeInsert Delete Getrandom O1 · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(1)# Space: O(n) from random import randint class RandomizedSet(object):     def __init__(self):        """        Initialize your data structure here.        """        self.__set = []        self.__used = {}      def insert(self, val):        """        Inserts a value to the set. Returns true if the set did not already contain the specified element.        :type val: int        :rtype: bool        """        if val in self.__used:            return False         self.__set += val,        self.__used[val] = len(self.__set)-1         return True      def remove(self, val):        """        Removes a value from the set. Returns true if the set contained the specified element.        :type val: int        :rtype: bool        """        if val not in self.__used:            return False         self.__used[self.__set[-1]] = self.__used[val]        self.__set[self.__used[val]], self.__set[-1] = self.__set[-1], self.__set[self.__used[val]]         self.__used.pop(val)        self.__set.pop()         return True     def getRandom(self):        """        Get a random element from the set.        :rtype: int        """        return self.__set[randint(0, len(self.__set)-1)]    

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗