Skip to content
Programmingoneonone
Programmingoneonone
  • CS Subjects
    • Internet of Things (IoT)
    • Digital Communication
    • Human Values
    • Cybersecurity
  • Programming Tutorials
    • C Programming
    • Data structures and Algorithms
    • 100+ Java Programs
    • 100+ C Programs
  • HackerRank Solutions
    • HackerRank Algorithms Solutions
    • HackerRank C problems solutions
    • HackerRank C++ problems solutions
    • HackerRank Java problems solutions
    • HackerRank Python problems solutions
Programmingoneonone
Programmingoneonone

HackerRank Queues: A Tale of Two Stacks solution

YASH PAL, 31 July 20246 February 2026

In this HackerRank Queues: A Tale of Two Stacks problem solution, 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:

  • x: Enqueue element x at the end of the queue.
  • Dequeue the element at the front of the queue.
  • Print the element at the front of the queue.
HackerRank Queues: A Tale of Two Stacks solution

HackerRank Queues: A Tale of Two Stacks solution in Python.

class MyQueue(object):
    def __init__(self):
        self.items=[]
    
    def peek(self):
        i = self.items.pop()
        self.items.append(i)
        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:
        queue.put(values[1])        
    elif values[0] == 2:
        queue.pop()
    else:
        print(queue.peek())
        

Queues: A Tale of Two Stacks solution in Java.

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


public class Solution {
    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
              queue.enqueue(scan.nextInt());
            } else if (operation == 2) { // dequeue
              queue.dequeue();
            } else if (operation == 3) { // print/peek
              System.out.println(queue.peek());
            }
        }
        scan.close();
    }
    
    static class MyQueue<T> {
        private Stack<T> reversed;
        private Stack<T> normal;

        public MyQueue() {
            normal = new Stack<>();
            reversed = new Stack<>();
        }

        public void enqueue(T item) {
            reversed.push(item);
        }

        private void pour() {
            while (!reversed.isEmpty()) {
                normal.push(reversed.pop());
            }
        }

        public T peek() {
            if (normal.isEmpty()) { pour(); }
            return normal.peek();
        }

        public T dequeue() {
            if (normal.isEmpty()) { pour(); }
            return normal.pop();
        }
    }

}

Problem solution in C++ programming.

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

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

        void pop() {
            prepOld();
            stack_oldest_on_top.pop();
            prepNew();
        }

        int front() {
            prepOld();
            return stack_oldest_on_top.top();
            prepNew();
        }

        void prepOld(){
            if (stack_oldest_on_top.empty())
            {   
                while(!stack_newest_on_top.empty())
                {
                    stack_oldest_on_top.push(stack_newest_on_top.top());
                    stack_newest_on_top.pop();
                }
            }
        }
        void prepNew(){
            if (stack_newest_on_top.empty())
            {   
                while(!stack_oldest_on_top.empty())
                {
                    stack_newest_on_top.push(stack_oldest_on_top.top());
                    stack_oldest_on_top.pop();
                }
            }
        }

};

int main() {
    MyQueue q1;
    int q, type, x;
    cin >> q;
    
    for(int i = 0; i < q; i++) {
        cin >> type;
        if(type == 1) {
            cin >> x;
            q1.push(x);
        }
        else if(type == 2) {
            q1.pop();
        }
        else cout << q1.front() << endl;
    }
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  

    return 0;
}

Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define MAX 100000

typedef struct {
    int first;
    int last;
    int data[MAX];
} Q;

void Init(Q* q) {
    q->first = 0;
    q->last  = MAX - 1;
}

void Enqueue(Q* q, int val) {
    q->last = (q->last + 1) % MAX;
    q->data[q->last] = val;
}

int Dqueue(Q* q) {
    int val = q->data[q->first];
    q->first = (q->first + 1) % MAX;
    return val;
}

void PrintHead(Q* q) {
    printf("%dn", q->data[q->first]);
}

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    Q q;
    Init(&q);
    int n;
    scanf("%d", &n);
    
    for(int i = 0; i < n; i++){
        int op, val;
        scanf("%d", &op);
        switch(op) {
            case 1:
                scanf("%d", &val);
                Enqueue(&q, val);
                break;
            case 2:
                Dqueue(&q);
                break;
            case 3:
                PrintHead(&q);
                break;
        }
    }
    return 0;
}

Problem solution in JavaScript programming.

function processData(input) {
    let inbox = [];
    let outbox = [];
    let operations = input.split('n').slice(1).map(line => { return line.split(' ') });
    for (let i = 0; i < operations.length; i++) {
        if (operations[i].length == 2) {
            inbox.push(operations[i][1]);
        } else {
            if (outbox.length === 0) {
                while (inbox.length > 0) {
                    outbox.push(inbox.pop());
                }
            }
            if (operations[i][0] === '2') {
                outbox.pop();
            } else {
                console.log(outbox[outbox.length - 1]);
            }
        }
    }
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

coding problems solutions Hackerrank Problems Solutions interview prepration kit HackerRank

Post navigation

Previous post
Next post

Pages

  • About US
  • Contact US
  • Privacy Policy

Follow US

  • YouTube
  • LinkedIn
  • Facebook
  • Pinterest
  • Instagram
©2026 Programmingoneonone | WordPress Theme by SuperbThemes