Consider the following statements : S1 : A queue can be implemented using two…

2016

Consider the following statements :

S1 : A queue can be implemented using two stacks.

S2 : A stack can be implemented using two queues.

Which of the following is correct ?

  1. A.

    S1 is correct and S2 is not correct.

  2. B.

    S1 is not correct and S2 is correct.

  3. C.

    Both S1 and S2 are correct.

  4. D.

    Both S1 and S2 are not correct.

Attempted by 990 students.

Show answer & explanation

Correct answer: C

Answer: Both statements are correct.

  • Implementing a queue using two stacks (amortized O(1) per operation):

    1. Maintain two stacks: stack_in and stack_out.

    2. Enqueue(x): push x onto stack_in.

    3. Dequeue(): if stack_out is empty, pop all elements from stack_in and push them onto stack_out; then pop from stack_out.

    Complexity: Amortized O(1) per enqueue/dequeue because each element is moved at most once between stacks.

  • Implementing a stack using two queues (example: push-costly method):

    1. Maintain two queues: q1 (holds current stack order) and q2 (temporary).

    2. Push(x): enqueue x into q2, then dequeue all elements from q1 and enqueue them into q2; swap q1 and q2. Now q1 has the new element at the front (top of stack).

    3. Pop(): dequeue from q1 (this returns the last pushed element).

    Complexity: Push is O(n) and pop is O(1) in this method. There is an alternative (pop-costly) method where push is O(1) and pop is O(n).

Explore the full course: Coding For Placement