Data structure: insert, remove, contains, get random element, all at O(1)

后端 未结 14 734
别跟我提以往
别跟我提以往 2020-11-29 14:53

I was given this problem in an interview. How would you have answered?

Design a data structure that offers the following operations in O(1) time:

  • inse
14条回答
  •  伪装坚强ぢ
    2020-11-29 15:16

    The best solution is probably the hash table + array, it's real fast and deterministic.

    But the lowest rated answer (just use a hash table!) is actually great too!

    • hash table with re-hashing, or new bucket selection (i.e. one element per bucket, no linked lists)
    • getRandom() repeatedly tries to pick a random bucket until it's empty.
    • as a fail-safe, maybe getRandom(), after N (number of elements) unsuccessful tries, picks a random index i in [0, N-1] and then goes through the hash table linearly and picks the #i-th element.

    People might not like this because of "possible infinite loops", and I've seen very smart people have this reaction too, but it's wrong! Infinitely unlikely events just don't happen.

    Assuming the good behavior of your pseudo-random source -- which is not hard to establish for this particular behavior -- and that hash tables are always at least 20% full, it's easy to see that:

    It will never happen that getRandom() has to try more than 1000 times. Just never. Indeed, the probability of such an event is 0.8^1000, which is 10^-97 -- so we'd have to repeat it 10^88 times to have one chance in a billion of it ever happening once. Even if this program was running full-time on all computers of humankind until the Sun dies, this will never happen.

提交回复
热议问题