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

后端 未结 14 731
别跟我提以往
别跟我提以往 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:14

    We can use hashing to support operations in Θ(1) time.

    insert(x) 1) Check if x is already present by doing a hash map lookup. 2) If not present, then insert it at the end of the array. 3) Add in hash table also, x is added as key and last array index as index.

    remove(x) 1) Check if x is present by doing a hash map lookup. 2) If present, then find its index and remove it from hash map. 3) Swap the last element with this element in array and remove the last element. Swapping is done because the last element can be removed in O(1) time. 4) Update index of last element in hash map.

    getRandom() 1) Generate a random number from 0 to last index. 2) Return the array element at the randomly generated index.

    search(x) Do a lookup for x in hash map.

提交回复
热议问题