Insert Delete GetRandom O(1)
Implement a data structure that supports insert(val), remove(val), and getRandom() in average O(1) time.
- insert returns True if val was not present
- remove returns True if val was present
- getRandom returns a random element (for testing, return the element at index 0)
Output results of each operation.
Example
insert,1;remove,2;insert,2;getRandom;remove,1;insert,2;getRandom
True False True 1 True False 2
- We start with an empty data structure and perform the operations in sequence:
insert(1)returnsTruebecause 1 is not present. remove(2)returnsFalsebecause 2 is not present, andinsert(2)returnsTruebecause 2 was not present, resulting in the data structure containing [1, 2].getRandom()returns the element at index 0, which is1, andremove(1)returnsTruebecause 1 was present, leaving [2] in the data structure.- Finally,
insert(2)returnsFalsebecause 2 is already present, andgetRandom()returns the element at index 0, which is2.
Constraints
- -2^31 <= val <= 2^31 - 1
- At most 2 * 10^5 operations