- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 56 lines of Python from the credited upstream file insert-delete-getrandom-o1-duplicates-allowed.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
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 randint5from collections import defaultdict6 7class RandomizedCollection(object):8 9 def __init__(self):10 """11 Initialize your data structure here.12 """13 self.__list = []14 self.__used = defaultdict(list)15 16 17 def insert(self, val):18 """19 Inserts a value to the collection. Returns true if the collection did not already contain the specified element.20 :type val: int21 :rtype: bool22 """23 has = val in self.__used24 25 self.__list += (val, len(self.__used[val])),26 self.__used[val] += len(self.__list)-1,27 28 return not has29 30 31 def remove(self, val):32 """33 Removes a value from the collection. Returns true if the collection contained the specified element.34 :type val: int35 :rtype: bool36 """37 if val not in self.__used:38 return False39 40 self.__used[self.__list[-1][0]][self.__list[-1][1]] = self.__used[val][-1]41 self.__list[self.__used[val][-1]], self.__list[-1] = self.__list[-1], self.__list[self.__used[val][-1]]42 43 self.__used[val].pop()44 if not self.__used[val]:45 self.__used.pop(val)46 self.__list.pop()47 48 return True49 50 def getRandom(self):51 """52 Get a random element from the collection.53 :rtype: int54 """55 return self.__list[randint(0, len(self.__list)-1)][0]56