Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

  • insert
  • remove
  • contains
  • get random element
like image 203
guildner Avatar asked Apr 15 '11 20:04

guildner


People also ask

Which data structure inserts and deletes in O 1 time?

The Insertion, deletion and searching will take O(1) amount of time. To solve this problem, we will use one Boolean array.

In which data structure we can delete insert element easily?

Stack is a linear data structure in which the insertion and deletion operations are performed at only one end. In a stack, adding and removing of elements are performed at single position which is known as "top". That means, new element is added at top of the stack and an element is removed from the top of the stack.


1 Answers

Consider a data structure composed of a hashtable H and an array A. The hashtable keys are the elements in the data structure, and the values are their positions in the array.

  1. insert(value): append the value to array and let i be its index in A. Set H[value]=i.
  2. remove(value): We are going to replace the cell that contains value in A with the last element in A. let d be the last element in the array A at index m. let i be H[value], the index in the array of the value to be removed. Set A[i]=d, H[d]=i, decrease the size of the array by one, and remove value from H.
  3. contains(value): return H.contains(value)
  4. getRandomElement(): let r=random(current size of A). return A[r].

since the array needs to auto-increase in size, it's going to be amortize O(1) to add an element, but I guess that's OK.

like image 63
r0u1i Avatar answered Sep 22 '22 14:09

r0u1i