Given an integer k and a queue q of integers, reverse the order of the first k elements of the queue, leaving the other elements in the same relative order.
Only following standard operations are allowed on the queue.Â
- enqueue(x): Add an item x to rear of queue
- dequeue(): Remove an item from the front of the queue
- size(): Returns the number of elements in the queue.
- front(): Finds front item.
Example:
Input: q = 1 2 3 4 5, k = 3
Output: 3 2 1 4 5
Explanation: After reversing the first 3 elements from the given queue the resultant queue will be 3 2 1 4 5.Input: q = 4 3 2 1, k= 4
Output: 1 2 3 4
Explanation: After reversing the first 4 elements from the given queue the resultant queue will be 1 2 3 4.
Table of Content
[Approach - 1] - Using the Recursion Call Stack - O(n)Time O(n)Space
The idea is to remove and store the first k elements in recursive call stack and insert them in the queue in the reverse order then we can simply remove and add remaining items of the queue.
Algorithm:
- Recursively remove the first k elements, then add them back during backtracking → this reverses their order.
- Rotate the remaining (n − k) elements from front to back → to maintain their original order.
#include <iostream>
#include<vector>
using namespace std;
void moveKToEnd(queue<int>& q, int k) {
if (k == 0) return;
int e = q.front();
q.pop();
moveKToEnd(q, k - 1);
q.push(e);
}
// Main function to reverse first k elements of a queue
queue<int> reverseFirstK(queue<int> q, int k) {
moveKToEnd(q, k);
int s = q.size() - k;
while (s-- > 0) {
int x = q.front();
q.pop();
q.push(x);
}
return q;
}
int main() {
queue<int> queue;
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
int k = 3;
queue = reverseFirstK(queue, k);
// Printing queue
while (!queue.empty()) {
cout << queue.front() << " ";
queue.pop();
}
return 0;
}
import java.util.Queue;
import java.util.LinkedList;
public class GfG {
// Function to reverse first k elements of a queue.
static Queue<Integer> reverseFirstK(Queue<Integer> q, int k) {
moveKToEnd(q, k);
int s = q.size() - k;
while( s-- > 0){
int x = q.poll();
q.add(x);
}
return q;
}
static void moveKToEnd(Queue<Integer> q, int k){
if(k == 0) return;
int e = q.poll();
moveKToEnd(q, k - 1);
q.add(e);
}
// driver code
public static void main (String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(1);
queue.add(2);
queue.add(3);
queue.add(4);
queue.add(5);
int k = 3;
queue = reverseFirstK(queue, k);
// printing queue
while (!queue.isEmpty()) {
System.out.print(queue.poll() + " ");
}
}
}
from collections import deque
def reverse_first_k(q, k):
move_k_to_end(q, k)
s = len(q) - k
for _ in range(s):
x = q.popleft()
q.append(x)
return q
def move_k_to_end(q, k):
if k == 0:
return
e = q.popleft()
move_k_to_end(q, k - 1)
q.append(e)
if __name__ == "__main__":
queue = deque([1, 2, 3, 4, 5])
k = 3
queue = reverse_first_k(queue, k)
while queue:
print(queue.popleft(), end=' ')
using System;
using System.Collections.Generic;
class GfG {
public static LinkedList<int> queue;
public static void moveKToEnd(int k) {
if (k == 0){
return;
}
int e = queue.First.Value;
queue.RemoveFirst();
moveKToEnd(k - 1);
queue.AddLast(e);
}
// Function to reverse first k elements of a queue
public static void reverseFirstK(int k) {
moveKToEnd(k);
int s = queue.Count - k;
while (s > 0) {
int x = queue.First.Value;
queue.RemoveFirst();
queue.AddLast(x);
s = s - 1;
}
}
// Driver code
public static void Main(string[] args) {
queue = new LinkedList<int>();
queue.AddLast(1);
queue.AddLast(2);
queue.AddLast(3);
queue.AddLast(4);
queue.AddLast(5);
int k = 3;
reverseFirstK(k);
// Printing queue
while (queue.Count > 0)
{
Console.Write(queue.First.Value + " ");
queue.RemoveFirst();
}
}
}
class Queue {
constructor() { this.items = []; }
// add element to the queue
push(element) { return this.items.push(element); }
// remove element from the queue
pop()
{
if (this.items.length > 0) {
return this.items.shift();
}
}
// view the first element
front() { return this.items[0]; }
// check if the queue is empty
isEmpty() { return this.items.length == 0; }
// the size of the queue
size() { return this.items.length; }
}
// Function to reverse first k elements of a queue
function reverseFirstK(queue, k)
{
moveKToEnd(queue, k);
let s = queue.size() - k;
while (s-- > 0) {
let x = queue.front();
queue.pop();
queue.push(x);
}
return queue;
}
function moveKToEnd(queue, k)
{
if (k == 0)
return;
let e = queue.front();
queue.pop();
moveKToEnd(queue, k - 1);
queue.push(e);
}
// Driver code
let queue = new Queue();
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
let k = 3;
q = reverseFirstK(queue, k);
// Printing queue
while (!q.isEmpty()) {
console.log(q.front());
q.pop();
}
Output
3 2 1 4 5
[Approach - 2] - Using a Stack - O(n + k)Time O(k)Space
The idea is to use an auxiliary stack. Remove(dequeue) the first k elements from the queue and push them in a stack after this pop the elements from the stack and add(enqueue) them to the queue , after that simply remove(dequeue) the remaining n-k elements from the queue and add(enqueue) them back to the queue.
Algorithm:
- Create an empty stack.
- One by one dequeue first K items from given queue and push the dequeued items to stack.
- Enqueue the contents of stack at the back of the queue
- Dequeue (size-k) elements from the front and enqueue them one by one to the same queue.
#include <iostream>
#include<vector>
using namespace std;
// Function to reverse the first
// K elements of the Queue
void reverseFirstK(queue<int>& q, int k)
{
if (q.empty() == true || k > q.size())
return;
if (k <= 0)
return;
stack<int> s;
// Push the first K elements
// into a Stack
for (int i = 0; i < k; i++) {
s.push(q.front());
q.pop();
}
// Enqueue the contents of stack
// at the back of the queue
while (!s.empty()) {
q.push(s.top());
s.pop();
}
// Remove the remaining elements and
// enqueue them at the end of the Queue
for (int i = 0; i < q.size() - k; i++) {
q.push(q.front());
q.pop();
}
}
// Utility Function to print the Queue
void Print(queue<int>& q)
{
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
}
int main()
{
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
int k = 3;
reverseFirstK(q, k);
Print(q);
}
import java.util.Queue;
import java.util.Stack;
import java.util.LinkedList;
public class GFG {
// Function to reverse the first
// K elements of the Queue
static void reverseFirstK(Queue<Integer> q, int k) {
if (q.isEmpty() || k > q.size())
return;
if (k <= 0)
return;
Stack<Integer> s = new Stack<>();
// Push the first K elements
// into a Stack
for (int i = 0; i < k; i++) {
s.push(q.poll());
}
// Enqueue the contents of stack
// at the back of the queue
while (!s.isEmpty()) {
q.add(s.pop());
}
// Remove the remaining elements and
// enqueue them at the end of the Queue
for (int i = 0; i < q.size() - k; i++) {
q.add(q.poll());
}
}
// Utility Function to print the Queue
static void print(Queue<Integer> q) {
while (!q.isEmpty()) {
System.out.print(q.poll() + " ");
}
}
public static void main(String[] args) {
Queue<Integer> q = new LinkedList<>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
int k = 3;
reverseFirstK(q, k);
print(q);
}
}
from collections import deque
# Function to reverse the first K elements of the Queue
def reverseFirstK(q, k):
if not q or k > len(q):
return
if k <= 0:
return
s = []
# Push the first K elements into a Stack
for _ in range(k):
s.append(q.popleft())
# Enqueue the contents of stack at the back of the queue
while s:
q.append(s.pop())
# Remove the remaining elements and enqueue them at the end of the Queue
for _ in range(len(q) - k):
q.append(q.popleft())
# Utility Function to print the Queue
def printQueue(q):
while q:
print(q.popleft(), end=' ')
if __name__ == '__main__':
q = deque()
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
k = 3
reverseFirstK(q, k)
printQueue(q)
using System;
using System.Collections.Generic;
class GfG {
// Function to reverse the first
// K elements of the Queue
static void ReverseFirstK(Queue<int> q, int k) {
if (q.Count == 0 || k > q.Count)
return;
if (k <= 0)
return;
Stack<int> s = new Stack<int>();
// Push the first K elements
// into a Stack
for (int i = 0; i < k; i++) {
s.Push(q.Dequeue());
}
// Enqueue the contents of stack
// at the back of the queue
while (s.Count > 0) {
q.Enqueue(s.Pop());
}
// Remove the remaining elements and
// enqueue them at the end of the Queue
for (int i = 0; i < q.Count - k; i++) {
q.Enqueue(q.Dequeue());
}
}
// Utility Function to print the Queue
static void Print(Queue<int> q) {
while (q.Count > 0) {
Console.Write(q.Dequeue() + " ");
}
}
static void Main() {
Queue<int> q = new Queue<int>();
q.Enqueue(1);
q.Enqueue(2);
q.Enqueue(3);
q.Enqueue(4);
q.Enqueue(5);
int k = 3;
ReverseFirstK(q, k);
Print(q);
}
}
function reverseFirstK(q, k) {
if (q.length === 0 || k > q.length)
return;
if (k <= 0)
return;
let s = [];
// Push the first K elements
// into a Stack
for (let i = 0; i < k; i++) {
s.push(q.shift());
}
// Enqueue the contents of stack
// at the back of the queue
while (s.length > 0) {
q.push(s.pop());
}
// Remove the remaining elements and
// enqueue them at the end of the Queue
for (let i = 0; i < q.length - k; i++) {
q.push(q.shift());
}
}
// Utility Function to print the Queue //
function printQueue(q) {
while (q.length > 0) {
process.stdout.write(q.shift() + ' ');
}
}
// Driver code
let q = [];
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
let k = 3;
reverseFirstK(q, k);
printQueue(q);
Output
3 2 1 4 5
Time Complexity: O(n + k), Where 'n' is the total number of elements in the queue and 'k' is the number of elements to be reversed. This is because firstly the k elements from the queue is emptied into the stack and then added back to the queue from the stack after that first 'n-k' elements are emptied and enqueued back to the queue.
Auxiliary Space: O(k) due to the stack used to store the first k elements.