Pergunta de entrevista da empresa Slack

Implement a randomized set that contains insert, delete and get random operations that all take O(1)

Resposta da entrevista

Sigiloso

2 de jan. de 2024

Can use a couple of helper data structures to implement this. Use a hash map to keep a mapping of the element in the set and the index it is at in an array. Use an array to store all the elements in the set. Insert operation is as simple as checking if the map has an entry for the element (O(1)) and if not, adding any entry and placing the element at the end of the array. Remove involves swapping the indices of the element to be removed with the element that's currently at the end of the array, then removing the associated entry from the hash map. The get random operation simply returns an element from the array selected uniformly at random (this ensures that there is an equal probability that any element is selected)