Queues: A Tale of Two Stacks

Problem Statement :

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed.

A basic queue has the following operations:

Enqueue: add a new element to the end of the queue.
Dequeue: remove the element from the front of the queue and return it.

In this challenge, you must first implement a queue using two stacks. Then process q queries, where each query is one of the following 3 types:

1 x: Enqueue element  into the end of the queue.
2: Dequeue the element at the front of the queue.
3: Print the element at the front of the queue.

Function Description

Complete the put, pop, and peek methods in the editor below. They must perform the actions as described above.

Input Format

The first line contains a single integer, q, the number of queries.

Each of the next q lines contains a single query in the form described in the problem statement above. All queries start with an integer denoting the query type, but only query 1 is followed by an additional space-separated value, x, denoting the value to be enqueued.


1    <=     q   <=    10^5
1    <=    type   <=  3
1    <=    | x |   <=   10^9

It is guaranteed that a valid answer always exists for each query of types 2 and 3.

Output Format

For each query of type 3, return the value of the element at the front of the fifo queue on a new line.

Solution :


                            Solution in C :

In   C  :

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 10000000

int queue[MAX];
int front = -1;
int rear = -1;

void enqueue(int num){
    queue[++rear] = num;

void dequeue(){

void display(){

int main() {
    int n,i=0, choose,num;
            case 1:
                scanf("%d", &num);
            case 2:
            case 3:

    return 0;

                        Solution in C++ :

In   C++ :

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
using namespace std;

class MyQueue {
        stack<int> stack_newest_on_top, stack_oldest_on_top;   
        void push(int x) {

        void pop() {
            if (stack_oldest_on_top.empty()) {
                // copy over and pop                                
                while (!stack_newest_on_top.empty()) {              

        int front() { 
            if (stack_oldest_on_top.empty()) {
                // copy over and pop                                
                while (!stack_newest_on_top.empty()) {              
            return stack_oldest_on_top.top();            

int main() {
    MyQueue q1;
    int q, type, x;
    cin >> q;
    for(int i = 0; i < q; i++) {
        cin >> type;
        if(type == 1) {
            cin >> x;
        else if(type == 2) {
        else cout << q1.front() << endl;
    return 0;

                        Solution in Java :

In   Java :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static class MyQueue<T> {
        Stack<T> stack1 = new Stack<T>();
        Stack<T> stack2 = new Stack<T>();

        public void enqueue(T value) { // Push onto newest stack

        public T peek() {
             if (stack2.isEmpty()) {
                 while (!stack1.isEmpty()) {
            return stack2.peek();

        public T dequeue() {
            if (stack2.isEmpty()) {
                while(!stack1.isEmpty()) {
            return stack2.pop();

    public static void main(String[] args) {
        MyQueue<Integer> queue = new MyQueue<Integer>();
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        for (int i = 0; i < n; i++) {
            int operation = scan.nextInt();
            if (operation == 1) { // enqueue
            } else if (operation == 2) { // dequeue
            } else if (operation == 3) { // print/peek

                        Solution in Python : 
In   Python3  :

class MyQueue(object):
    def __init__(self):
    def peek(self):
        i = self.items.pop()
        return i
    def pop(self):
        return self.items.pop()
    def put(self, value):
        self.items.insert(0, value)

queue = MyQueue()
t = int(input())
for line in range(t):
    values = map(int, input().split())
    values = list(values)
    if values[0] == 1:
    elif values[0] == 2:

View More Similar Problems

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution →

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution →

Balanced Brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of bra

View Solution →

Equal Stacks

ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of

View Solution →