Search⌘ K
AI Features

Challenge: Implement Queue Using Stacks

Explore how to design a queue using only two stacks by implementing enqueue and dequeue functions. Understand the underlying concepts of stacks and queues through a practical coding challenge, strengthening your grasp of fundamental data structures in Python.

We'll cover the following...

Statement

Design a queue data structure using only two stacks and implement the following functions:

  • enqueue(int x): Inserts a value to the back of the queue.
  • dequeue(): Removes and returns the value from the front of the queue.

Constraints:

  • 105-10^5 \leq x 105\leq 10^5

Examples

canvasAnimation-image
1 / 3

Try it yourself

Implement your solution in the following coding playground.

Note: You may use the custom MyStack class provided in the code to simulate a stack.

Python
usercode > solution.py
from Stack import MyStack
# Push Function => stack.push(int) //Inserts the element at top
# Pop Function => stack.pop() //Removes and returns the element at top
# Top/Peek Function => stack.get_top() //Returns top element
# Helper Functions => stack.is_empty() & stack.isFull() //Returns boolean
class NewQueue:
def __init__(self):
self.main_stack = MyStack()
# Write your code here
# Inserts the element in the queue
def enqueue(self, value):
# Write your code here
pass
# Removes the element from the queue
def dequeue(self):
# Write your code here
pass
Implement Queue Using Stacks