v9.1.1
Menu

Insert Delete GetRandom O(1)

mediumPROArrays & MatricesApple DSA

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

Input
insert,1;remove,2;insert,2;getRandom;remove,1;insert,2;getRandom
Output
True
False
True
1
True
False
2
Reasoning
  • We start with an empty data structure and perform the operations in sequence: insert(1) returns True because 1 is not present.
  • remove(2) returns False because 2 is not present, and insert(2) returns True because 2 was not present, resulting in the data structure containing [1, 2].
  • getRandom() returns the element at index 0, which is 1, and remove(1) returns True because 1 was present, leaving [2] in the data structure.
  • Finally, insert(2) returns False because 2 is already present, and getRandom() returns the element at index 0, which is 2.

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 operations

More from Apple DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.