Bird
Raised Fist0
DSA C#programming~20 mins

Queue Using Two Stacks in DSA C# - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Queue Two Stacks Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Enqueue and Dequeue Operations
What is the printed state of the queue after performing these operations?

Enqueue 10, Enqueue 20, Dequeue, Enqueue 30, Dequeue
DSA C#
class QueueUsingStacks {
    private Stack<int> stack1 = new Stack<int>();
    private Stack<int> stack2 = new Stack<int>();

    public void Enqueue(int x) {
        stack1.Push(x);
    }

    public int Dequeue() {
        if (stack2.Count == 0) {
            while (stack1.Count > 0) {
                stack2.Push(stack1.Pop());
            }
        }
        return stack2.Pop();
    }

    public string PrintQueue() {
        var temp = new List<int>();
        foreach (var item in stack2) temp.Add(item);
        var s1 = new List<int>();
        foreach (var item in stack1) s1.Add(item);
        s1.Reverse();
        temp.AddRange(s1);
        return string.Join(" -> ", temp) + " -> null";
    }
}

var q = new QueueUsingStacks();
q.Enqueue(10);
q.Enqueue(20);
q.Dequeue();
q.Enqueue(30);
q.Dequeue();
Console.WriteLine(q.PrintQueue());
Anull
B20 -> 30 -> null
C10 -> 30 -> null
D30 -> null
Attempts:
2 left
💡 Hint
Remember that dequeue moves elements from stack1 to stack2 only when stack2 is empty.
🧠 Conceptual
intermediate
1:30remaining
Understanding Stack Transfers in Queue Implementation
Why do we transfer elements from stack1 to stack2 only when stack2 is empty during dequeue operation in a queue implemented using two stacks?
ATo reverse the order of elements so the oldest element is on top for dequeue.
BTo clear stack1 to save memory.
CTo sort the elements in ascending order before dequeue.
DTo duplicate elements for backup.
Attempts:
2 left
💡 Hint
Think about how stacks work and how queue order is maintained.
🔧 Debug
advanced
1:30remaining
Identify the Error in Dequeue Method
What error will occur when calling Dequeue on an empty queue implemented using two stacks with this code snippet?
DSA C#
public int Dequeue() {
    if (stack2.Count == 0) {
        while (stack1.Count > 0) {
            stack2.Push(stack1.Pop());
        }
    }
    return stack2.Pop();
}
ANullReferenceException because stack2 is null.
BInvalidOperationException due to popping from an empty stack.
CIndexOutOfRangeException because of invalid index access.
DNo error, returns default int value 0.
Attempts:
2 left
💡 Hint
What happens if both stacks are empty and you try to pop?
❓ Predict Output
advanced
2:00remaining
Final Queue State After Mixed Operations
What is the printed queue state after these operations?

Enqueue 5, Enqueue 15, Enqueue 25, Dequeue, Enqueue 35, Dequeue, Enqueue 45
DSA C#
class QueueUsingStacks {
    private Stack<int> stack1 = new Stack<int>();
    private Stack<int> stack2 = new Stack<int>();

    public void Enqueue(int x) {
        stack1.Push(x);
    }

    public int Dequeue() {
        if (stack2.Count == 0) {
            while (stack1.Count > 0) {
                stack2.Push(stack1.Pop());
            }
        }
        return stack2.Pop();
    }

    public string PrintQueue() {
        var temp = new List<int>();
        foreach (var item in stack2) temp.Add(item);
        var s1 = new List<int>();
        foreach (var item in stack1) s1.Add(item);
        s1.Reverse();
        temp.AddRange(s1);
        return string.Join(" -> ", temp) + " -> null";
    }
}

var q = new QueueUsingStacks();
q.Enqueue(5);
q.Enqueue(15);
q.Enqueue(25);
q.Dequeue();
q.Enqueue(35);
q.Dequeue();
q.Enqueue(45);
Console.WriteLine(q.PrintQueue());
A35 -> 45 -> null
B15 -> 25 -> 35 -> 45 -> null
C25 -> 35 -> 45 -> null
D5 -> 15 -> 25 -> 35 -> 45 -> null
Attempts:
2 left
💡 Hint
Track elements moved between stacks carefully after each dequeue.
🚀 Application
expert
1:30remaining
Time Complexity Analysis of Queue Using Two Stacks
What is the amortized time complexity of the Dequeue operation in a queue implemented using two stacks?
AO(1) amortized time per dequeue operation
BO(n) time for every dequeue operation
CO(log n) time per dequeue operation
DO(n^2) time in worst case
Attempts:
2 left
💡 Hint
Consider how many times each element is moved between stacks.

Practice

(1/5)
1. What is the main idea behind implementing a Queue using two stacks?
easy
A. Use one stack for enqueue and another for dequeue operations
B. Use two stacks to store elements in sorted order
C. Use two stacks to reverse the order twice to maintain queue order
D. Use two stacks to store only even and odd elements separately

Solution

  1. Step 1: Understand queue order

    A queue follows First-In-First-Out (FIFO) order, meaning the first element added is the first removed.
  2. Step 2: Use two stacks to reverse order twice

    One stack reverses the order when pushing elements, and the second stack reverses it back when popping, maintaining FIFO.
  3. Final Answer:

    Use two stacks to reverse the order twice to maintain queue order -> Option C
  4. Quick Check:

    Two reversals keep FIFO order [OK]
Hint: Two stacks reverse order twice to simulate queue [OK]
Common Mistakes:
  • Thinking stacks store sorted elements
  • Using stacks for separate data types
  • Confusing enqueue and dequeue roles
2. Which of the following is the correct syntax to push an element 5 into a stack named stack1 in C#?
easy
A. stack1.Push(5);
B. stack1.Add(5);
C. stack1.Insert(5);
D. stack1.Enqueue(5);

Solution

  1. Step 1: Recall stack push method

    In C#, the Stack<T> class uses the Push method to add elements.
  2. Step 2: Check method names

    Add and Insert are not stack methods; Enqueue is for queues.
  3. Final Answer:

    stack1.Push(5); -> Option A
  4. Quick Check:

    Stack push method = Push() [OK]
Hint: Use Push() to add elements to stack [OK]
Common Mistakes:
  • Using Add() or Insert() which are not stack methods
  • Confusing Enqueue() with Push()
  • Using wrong method names
3. What will be the output of the following C# code implementing a queue using two stacks?
var queue = new QueueUsingTwoStacks();
queue.Enqueue(10);
queue.Enqueue(20);
queue.Enqueue(30);
Console.WriteLine(queue.Dequeue());
queue.Enqueue(40);
Console.WriteLine(queue.Dequeue());
medium
A. 30\n40
B. 10\n20
C. 20\n30
D. 10\n30

Solution

  1. Step 1: Enqueue elements 10, 20, 30

    Elements are pushed into the first stack in order: 10, then 20, then 30.
  2. Step 2: Dequeue operation

    On dequeue, elements are popped from the second stack after transferring from the first, so 10 is dequeued first.
  3. Step 3: Enqueue 40 and dequeue again

    40 is pushed into the first stack. Next dequeue returns 20, the next in queue order.
  4. Final Answer:

    10 20 -> Option B
  5. Quick Check:

    FIFO order maintained: 10 then 20 [OK]
Hint: Dequeue returns oldest enqueued element first [OK]
Common Mistakes:
  • Assuming dequeue returns last pushed element
  • Not transferring elements between stacks correctly
  • Mixing enqueue and dequeue order
4. Identify the error in the following C# code snippet for dequeue operation in a queue using two stacks:
public int Dequeue()
{
    if (stack2.Count == 0)
    {
        while (stack1.Count > 0)
            stack2.Push(stack1.Pop());
    }
    return stack1.Pop();
}
medium
A. Should pop from stack2, not stack1, after transfer
B. Should check if stack1 is empty before popping
C. Should push elements back to stack1 after popping
D. Should use Peek() instead of Pop()

Solution

  1. Step 1: Understand dequeue logic

    After transferring elements from stack1 to stack2, dequeue should pop from stack2 to maintain correct order.
  2. Step 2: Identify wrong pop call

    The code incorrectly pops from stack1 instead of stack2 after transfer.
  3. Final Answer:

    Should pop from stack2, not stack1, after transfer -> Option A
  4. Quick Check:

    Pop from stack2 after transfer [OK]
Hint: Pop from second stack after transfer for dequeue [OK]
Common Mistakes:
  • Popping from wrong stack after transfer
  • Not checking if stacks are empty
  • Using Peek() instead of Pop() for dequeue
5. You want to implement a queue using two stacks where Enqueue is O(1) time and Dequeue is amortized O(1). Which approach is best?
hard
A. Push elements to stack2 on enqueue; pop from stack1 on dequeue
B. Push elements alternately to stack1 and stack2 on enqueue; pop from stack1 on dequeue
C. Push elements to stack1 on enqueue; pop from stack1 on dequeue without transfer
D. Push all elements to stack1 on enqueue; transfer to stack2 only when stack2 is empty during dequeue

Solution

  1. Step 1: Understand enqueue O(1) requirement

    Enqueue should just push to stack1 without extra operations for O(1) time.
  2. Step 2: Understand dequeue amortized O(1)

    Dequeue transfers elements from stack1 to stack2 only when stack2 is empty, making transfers infrequent and amortized O(1).
  3. Step 3: Evaluate options

    Push all elements to stack1 on enqueue; transfer to stack2 only when stack2 is empty during dequeue matches this approach; others do not maintain correct order or time complexity.
  4. Final Answer:

    Push all elements to stack1 on enqueue; transfer to stack2 only when stack2 is empty during dequeue -> Option D
  5. Quick Check:

    Lazy transfer on dequeue gives amortized O(1) [OK]
Hint: Transfer only when needed on dequeue for amortized O(1) [OK]
Common Mistakes:
  • Transferring on every enqueue causing O(n) enqueue
  • Popping from wrong stack without transfer
  • Alternating pushes breaking queue order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard