Applied AI Engineer (LLM) coding learning path Level 3 This level · 2 of 27

Insert Delete GetRandom O(1)

Medium Design Array Hash map

Problem

Design a set that supports insert, remove and getRandom, each in average O(1) time. getRandom should return each current element with equal probability.

Original: LeetCode 380: Insert Delete GetRandom O(1).

Examples

Example 1

Input`RandomizedSet: insert(1), remove(2), insert(2), getRandom(), remove(1), insert(2), getRandom()`
Output`[null, true, false, true, 1 or 2, true, false, 2]`

Constraints

  • -2^31 <= val <= 2^31 - 1
  • At most 2 * 10^5 calls will be made to insert, remove, and getRandom.
  • There will be at least one element in the data structure when getRandom is called.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 380: Insert Delete GetRandom O(1)leetcode.com
  2. Java SE 17 API: Random.nextIntdocs.oracle.com
Previous
Next