3,971 views
7 votes
7 votes
Q.What will be time complexity of enqueue and dequeue operation when a queue is implemented using two stacks.

1 Answer

Best answer
7 votes
7 votes

The time complexity of enqueue and dequeue operation when using 2 stacks

If here enqueue using 2 stacks, then dequeue will use 1 stack is enough

Say, for enqueue we use reverse, push , reverse operations

  • So, in reversing all element will push in another stack take O(n) time
  • New element will be push ,take O(1) time
  • Then push back to the 1st stack will take O(n) time

Now in case of dequeue

  • just do pop the element from the front of stack(It will just take O(1) time)

_____________________________________________________________________

We can also do in reverse way, that take enqueue operation in O(1) time and dequeue O(n) time

edited by

Related questions

6 votes
6 votes
2 answers
3
SSrawat asked Oct 9, 2017
6,020 views
A queue is implemented using 2 stacks. Minimum no. of stack operations (PUSH and POP) required for the sequence of 3 insertions and 2 delete operations in the queue is ...
2 votes
2 votes
2 answers
4