AlgoDaily

Two Stack Queue

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

Building a Queue with Two Stacks: A Challenge in Engineering Elegance

The Objective: Queue with Stacks

In this challenge, your task is to implement a queue using two stacks. While many programming languages offer queues through arrays or lists, we're restricting our approach to only utilize stacks.

The end result should behave like this:

const tsq = new TwoStackQueue();
tsq.push(1);
tsq.push(2);
tsq.pop();  // Should return 1
tsq.pop();  // Should return 2
The Blueprint: Visualizing the Mechanics

Imagine having two stacks that work in harmony to simulate a queue. These stacks are like two components of a complex machine, each with its own specific role.

Two Stack Queue

Constraints and Expectations

Let's clarify the rules of the game:

  • Number of Operations: The maximum number of operations won't exceed 100,000.
  • Value Ranges: The elements you push onto the stack will range between -1,000,000,000 and 1,000,000,000.
  • Time Complexity for Push: If the pop operation has a time complexity of O(n), then the push operation should be O(1). Otherwise, the time complexity for push should be O(n).
  • Time Complexity for Pop: If the push operation has a time complexity of O(n), then the pop operation should be O(1). Otherwise, it should be O(n).
  • Space Complexity: Expected to be O(n).
```javascript
class TwoStackQueue {
  def __init__(self):
    self.inbox = []
    self.outbox = []
  }

  def push():
    # fill in
    return
  
  def pop():
    # fill in
    return
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →