Insert Delete GetRandom O(1) - Duplicates allowed

Solution Code
def remove(self, val: int) -> bool:
        if val not in self.idx or not self.idx[val]:
            return False
        remove_idx = next(iter(self.idx[val]))
        last = self.lst[-1]
        
        self.lst[remove_idx] = last
        self.idx[last].add(remove_idx)
        self.idx[last].discard(len(self.lst) - 1)
        
        self.idx[val].discard(remove_idx)
        self.lst.pop()
        return True

    def getRandom(self) -> int:
        return random.choice(self.lst)

Time Complexity

O(1) on average for all operations

Space Complexity

O(N) where N is the number of elements