- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- 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.
Use this to learn the idea, then write your own version.
123 4from random import randint5 6class RandomizedSet(object):7 8 def __init__(self):9 """10 Initialize your data structure here.11 """12 self.__set = []13 self.__used = {}14 15 16 def insert(self, val):17 """18 Inserts a value to the set. Returns true if the set did not already contain the specified element.19 :type val: int20 :rtype: bool21 """22 if val in self.__used:23 return False24 25 self.__set += val,26 self.__used[val] = len(self.__set)-127 28 return True29 30 31 def remove(self, val):32 """33 Removes a value from the set. Returns true if the set contained the specified element.34 :type val: int35 :rtype: bool36 """37 if val not in self.__used:38 return False39 40 self.__used[self.__set[-1]] = self.__used[val]41 self.__set[self.__used[val]], self.__set[-1] = self.__set[-1], self.__set[self.__used[val]]42 43 self.__used.pop(val)44 self.__set.pop()45 46 return True47 48 def getRandom(self):49 """50 Get a random element from the set.51 :rtype: int52 """53 return self.__set[randint(0, len(self.__set)-1)]54 55 56 57