Bird
Raised Fist0
DSA Goprogramming

Implement Stack Using Queue in DSA Go

Choose your learning style10 modes available
Mental Model
A stack works like a pile where you add and remove from the top. A queue works like a line where you add at the back and remove from the front. To make a stack using a queue, we reorder the queue so the last added item is always at the front.
Analogy: Imagine a line of people where the newest person always moves to the front of the line so they get served first, just like a stack where the last item added is the first to be removed.
Queue: front -> [1] -> 2 -> 3 -> back
Stack: top -> [3] -> 2 -> 1 -> bottom
Dry Run Walkthrough
Input: Push 1, Push 2, Push 3, Pop
Goal: Use a queue to behave like a stack and show the top element after each operation
Step 1: Push 1: enqueue 1
Queue: front -> [1] -> back
Why: Add first element to queue
Step 2: Push 2: enqueue 2, then rotate queue to move 2 to front
Queue: front -> [2] -> 1 -> back
Why: Rotate so last pushed is at front to simulate stack top
Step 3: Push 3: enqueue 3, then rotate queue to move 3 to front
Queue: front -> [3] -> 2 -> 1 -> back
Why: Rotate so last pushed is at front to simulate stack top
Step 4: Pop: dequeue front element (3)
Queue: front -> [2] -> 1 -> back
Why: Remove top element of stack which is front of queue
Result:
Queue after pop: front -> [2] -> 1 -> back
Popped element: 3
Annotated Code
DSA Go
package main

import (
	"container/list"
	"fmt"
)

type StackUsingQueue struct {
	queue *list.List
}

func NewStackUsingQueue() *StackUsingQueue {
	return &StackUsingQueue{queue: list.New()}
}

func (s *StackUsingQueue) Push(val int) {
	s.queue.PushBack(val) // enqueue new element at back
	// rotate queue to move new element to front
	for i := 0; i < s.queue.Len()-1; i++ {
		front := s.queue.Remove(s.queue.Front())
		s.queue.PushBack(front) // move front to back
	}
}

func (s *StackUsingQueue) Pop() int {
	if s.queue.Len() == 0 {
		return -1 // stack empty
	}
	front := s.queue.Remove(s.queue.Front()) // dequeue front element
	return front.(int)
}

func (s *StackUsingQueue) Top() int {
	if s.queue.Len() == 0 {
		return -1
	}
	return s.queue.Front().Value.(int)
}

func main() {
	stack := NewStackUsingQueue()
	stack.Push(1)
	fmt.Println("Top after push 1:", stack.Top())
	stack.Push(2)
	fmt.Println("Top after push 2:", stack.Top())
	stack.Push(3)
	fmt.Println("Top after push 3:", stack.Top())
	popped := stack.Pop()
	fmt.Println("Popped element:", popped)
	fmt.Println("Top after pop:", stack.Top())
}
s.queue.PushBack(val) // enqueue new element at back
add new element to the back of the queue
for i := 0; i < s.queue.Len()-1; i++ { front := s.queue.Remove(s.queue.Front()) s.queue.PushBack(front) // move front to back }
rotate queue to move last added element to front, simulating stack top
front := s.queue.Remove(s.queue.Front()) // dequeue front element
remove front element which is top of stack
OutputSuccess
Top after push 1: 1 Top after push 2: 2 Top after push 3: 3 Popped element: 3 Top after pop: 2
Complexity Analysis
Time: O(n) for push because we rotate the queue to reorder elements; O(1) for pop
Space: O(n) because we store all elements in the queue
vs Alternative: Compared to using two queues, this single queue approach uses less space but push is slower due to rotation
Edge Cases
Pop from empty stack
Returns -1 indicating stack is empty
DSA Go
if s.queue.Len() == 0 {
	return -1 // stack empty
}
Push single element
Element is added and becomes top immediately
DSA Go
s.queue.PushBack(val) // enqueue new element at back
When to Use This Pattern
When you need last-in-first-out behavior but only have a first-in-first-out structure, use queue rotation to simulate stack order.
Common Mistakes
Mistake: Not rotating the queue after push, so the top element is not at the front
Fix: Rotate the queue by moving front elements to back after each push to keep last pushed element at front
Mistake: Trying to pop from empty queue without check
Fix: Check if queue is empty before popping and handle gracefully
Summary
Implements a stack using a single queue by rotating elements to keep the last pushed item at the front.
Use when only queue operations are allowed but stack behavior is needed.
The key is to reorder the queue after each push so the newest element is always at the front.

Practice

(1/5)
1. What is the main idea behind implementing a stack using a queue?
easy
A. Use one or two queues to simulate Last-In-First-Out (LIFO) behavior
B. Use a queue to store elements in sorted order
C. Use a stack to simulate First-In-First-Out (FIFO) behavior
D. Use two stacks to implement a queue

Solution

  1. Step 1: Understand stack and queue behaviors

    A stack follows Last-In-First-Out (LIFO), while a queue follows First-In-First-Out (FIFO).
  2. Step 2: Simulate stack using queue(s)

    To implement a stack using queue(s), we use one or two queues to reorder elements so the last pushed element is always dequeued first.
  3. Final Answer:

    Use one or two queues to simulate Last-In-First-Out (LIFO) behavior -> Option A
  4. Quick Check:

    Stack = LIFO simulated by queue(s) [OK]
Hint: Remember stack is LIFO; queue is FIFO, reorder to simulate stack [OK]
Common Mistakes:
  • Confusing stack and queue order
  • Trying to sort elements instead of reordering
  • Using stack to implement queue instead
2. Which of the following is the correct Go syntax to declare a queue using a slice of integers?
easy
A. var queue []int
B. queue := make(map[int]int)
C. queue := []string{}
D. var queue int

Solution

  1. Step 1: Identify queue data structure type

    A queue can be implemented using a slice of integers for integer elements.
  2. Step 2: Check Go syntax for slice declaration

    "var queue []int" declares a slice of integers, suitable for queue implementation.
  3. Final Answer:

    var queue []int -> Option A
  4. Quick Check:

    Slice of int = queue [OK]
Hint: Use slice []int for queue of integers in Go [OK]
Common Mistakes:
  • Using map instead of slice for queue
  • Declaring wrong data type for queue
  • Using string slice for integer queue
3. Consider this Go code snippet implementing push operation of stack using one queue:
func (s *Stack) Push(x int) {
    s.q = append(s.q, x)
    for i := 0; i < len(s.q)-1; i++ {
        s.q = append(s.q, s.q[0])
        s.q = s.q[1:]
    }
}
If initially s.q = [1, 2], what is s.q after calling Push(3)?
medium
A. [3, 2, 1]
B. [1, 2, 3]
C. [3, 1, 2]
D. [2, 1, 3]

Solution

  1. Step 1: Append new element 3 to queue

    Initial queue: [1, 2]. After append: [1, 2, 3].
  2. Step 2: Rotate queue elements to move 3 to front

    Loop runs len(s.q)-1 = 2 times: - Iteration 1: append s.q[0]=1, queue becomes [1, 2, 3, 1], then remove first element: [2, 3, 1] - Iteration 2: append s.q[0]=2, queue becomes [2, 3, 1, 2], then remove first element: [3, 1, 2]
  3. Final Answer:

    [3, 1, 2] -> Option C
  4. Quick Check:

    Push moves new element front: [3,1,2] [OK]
Hint: New push rotates queue to front [OK]
Common Mistakes:
  • Not rotating queue after append
  • Removing wrong elements during rotation
  • Confusing order of elements after push
4. This Go code tries to implement Pop operation for stack using one queue:
func (s *Stack) Pop() int {
    if len(s.q) == 0 {
        return -1
    }
    val := s.q[0]
    s.q = s.q[1:]
    return val
}
What is the bug in this Pop method?
medium
A. It returns -1 when queue is empty, should panic instead
B. It removes the last element instead of the first
C. It does not check if queue is nil before accessing
D. It removes the front element, but stack pop should remove the last pushed element

Solution

  1. Step 1: Understand Pop operation in stack

    Pop removes the last pushed element (top of stack).
  2. Step 2: Analyze given Pop code

    Code removes s.q[0], the front of queue, which is incorrect because stack top is at front only if queue is rotated properly.
  3. Final Answer:

    It removes the front element, but stack pop should remove the last pushed element -> Option D
  4. Quick Check:

    Pop must remove last pushed, not front [OK]
Hint: Pop must remove top, not front element [OK]
Common Mistakes:
  • Removing front element without rotation
  • Ignoring empty queue check
  • Returning wrong default value
5. You want to implement a stack using two queues q1 and q2 in Go. Which approach correctly implements the Push operation to keep the stack order?
hard
A. Dequeue all elements from q1 to q2, then enqueue new element to q1
B. Enqueue new element to q2, then dequeue all from q1 to q2, swap q1 and q2
C. Enqueue new element to q1 only, no other operations
D. Enqueue new element to q1, then dequeue one element from q2

Solution

  1. Step 1: Understand two-queue stack push logic

    To keep stack order, new element must be at front of main queue after push.
  2. Step 2: Push by enqueue to empty q2, move all from q1 to q2, then swap

    Enqueue new element to q2, move all q1 elements to q2, then swap q1 and q2 so q1 has new order with new element front.
  3. Final Answer:

    Enqueue new element to q2, then dequeue all from q1 to q2, swap q1 and q2 -> Option B
  4. Quick Check:

    Push uses q2 enqueue + q1 transfer + swap [OK]
Hint: Push to empty q2, move q1 to q2, swap queues [OK]
Common Mistakes:
  • Not swapping queues after transfer
  • Enqueueing new element to wrong queue
  • Forgetting to move all elements
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