Vallabh Patade
Vallabh Patade

Reputation: 5110

Custom Data Structure for Push, Pop and Dequeue operations in Constant Time

I have asked this Question in one of the interview. Reproducing it.

Write custom DS where Push(),Pop() and Dequeue() operations will be done in constant time. e.g. input is 1,2,3,4 then we called pop(), 4 should be returned. If we call dequeue, 1 should be returned. Everything in O(1).

I have answered, but wasn't sure if that was best w.r.t. Space Complexity.

Upvotes: 0

Views: 744

Answers (1)

amit
amit

Reputation: 178451

doubly Linked List can provide it.

By having a pointer to both head and tail you can implement both dequeue() and pop() efficiently (O(1)).

Something along the lines of: (Assuming Garbage Collected language, and simplified version, not null/empty safe):

push(e):
  n = new Node(e)
  last.next = n
  n.previous = last
  last = n       
pop():
  e = last.value
  last.previous.next = null
  last = last.previous
  return e
dequeue():
  e = head.value
  head = head.next
  head.previous = null
  return e

Regarding space complexity:
The solution is Theta(n) space, it is easy to see that any sub-linear solution will not be able to store all the data - and will fail in some cases.

Upvotes: 6

Related Questions