In this Queue using Two Stacks HackerRank 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 queries, where each query is one of the following 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.
Input Format
The first line contains a single integer, , denoting the number of queries.
Each line of the subsequent lines contains a single query in the form described in the problem statement above. All three queries start with an integer denoting the query , but only query is followed by an additional space-separated value, , denoting the value to be enqueued.
Constraints
- It is guaranteed that a valid answer always exists for each query of type .
Output Format
For each query of type , print the value of the element at the front of the queue on a new line.
Sample Input
STDIN Function ----- -------- 10 q = 10 (number of queries) 1 42 1st query, enqueue 42 2 dequeue front element 1 14 enqueue 42 3 print the front element 1 28 enqueue 28 3 print the front element 1 60 enqueue 60 1 78 enqueue 78 2 dequeue front element 2 dequeue front element
Sample Output
14
14
Explanation
Perform the following sequence of actions:
- Enqueue ; .
- Dequeue the value at the head of the queue, ; .
- Enqueue ; .
- Print the value at the head of the queue, ; .
- Enqueue ; .
- Print the value at the head of the queue, ; .
- Enqueue ; .
- Enqueue ; .
- Dequeue the value at the head of the queue, ; .
- Dequeue the value at the head of the queue, ; .
Queue using Two Stacks HackerRank solution
I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.
Problem Solution in JavaScript
function processData(input) {
const [length, ...queries] = input.split('\n')
const [tail, head] = [[], []]
const moveTailToHead = () => {
while (tail.length) {
head.push(tail.pop())
}
}
for (let query of queries) {
if (query[0] == '1') { tail.push(query.split(' ')[1]) }
else if (query[0] == '2') { // Dequeue front element
if (!head.length) moveTailToHead()
head.pop()
}
else if (query[0] == '3') { // Print front element
if (!head.length) moveTailToHead()
console.log(head[head.length -1])
}
}
}
Problem Solution in Java
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();
int type;
Deque<Integer> deque = new ArrayDeque<>();
for (int i = 0; i < q; i++) {
type = scanner.nextInt();
switch (type) {
case 1:
deque.addLast(scanner.nextInt());
break;
case 2:
if (!deque.isEmpty())
deque.poll();
break;
case 3:
System.out.println(deque.peekFirst());
break;
}
}
Problem Solution in Python
class Queue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def enqueue(self, value):
self.stack1.append(value)
def dequeue(self, printFront=False):
if len(self.stack2) == 0:
while len(self.stack1) > 0:
self.stack2.append(self.stack1.pop())
if printFront:
return self.stack2[-1]
else:
return self.stack2.pop()
import os
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
queue = Queue()
t = int(input())
for t_itr in range(t):
query = input().split()
typ = query[0]
if typ == "1":
data = query[1]
queue.enqueue(data)
elif typ == "2":
_ = queue.dequeue()
else:
num = queue.dequeue(True)
fptr.write(num)
fptr.write('\n')
fptr.close()
Solve original Problem on HackerRank here. Checkout more HackerRank Problems