37 · Design Data Structures

#380 Insert Delete GetRandom O(1)

Mediumsolve on LeetCode ↗

frequently reported atBloombergUberLinkedInByteDance / TikTokAppleAmazon

the problem

In plain words

Build an integer set called RandomizedSet. insert(val) adds val if it is missing and tells you whether it was added. remove(val) deletes val if it is there and tells you whether it was deleted. getRandom() returns one of the values stored right now, each with the same chance; it is only called when the set is not empty. All three calls must take O(1) time on average.

in insert(1), remove(2), insert(2), getRandom(), remove(1), insert(2), getRandom()

out true, false, true, 1 or 2, true, false, 2

remove(2) fails because 2 isn't stored yet. After remove(1) only 2 is left, so the last getRandom must return 2.

  • −2³¹ ≤ val ≤ 2³¹ − 1
  • At most 2·10⁵ calls in total
  • getRandom is only called when the set holds at least one value

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

Design: implement every operation. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #528
      Random Pick with Weight
      Mediumin Math & Numbers
    2. #705
      Design HashSet
      Easyin Java OOP
    3. #146
      LRU Cache
      Mediumin Linked Lists
    4. #895
      Maximum Frequency Stack
      Hardin Design DS