Reversing the first K elements of a Queue
Last Updated :
24 Mar, 2025
Given an integer k and a queue of integers, The task is to 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.
Using the Recursion Call Stack - O(n) Time and 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.
C++
#include <bits/stdc++.h>
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;
}
Java
import java.io.*;
import java.util.*;
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() + " ");
}
}
}
Python
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)
queue = deque([1, 2, 3, 4, 5])
k = 3
queue = reverse_first_k(queue, k)
while queue:
print(queue.popleft(), end=' ')
C#
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();
}
}
}
JavaScript
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();
}
Time Complexity: O(n), function reverseFirstK calls the recursive function solve, which takes O(k) time to reverse the first k elements of the queue then the function reverseFirstK takes O(n-k) time to move the remaining elements to the end of the queue.
Auxiliary Space: O(n) , as the size of the call stack for the two recursive functions will O(k) and O(n-k).
Using a Stack - O(n+k) Time and 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.
C++
#include <bits/stdc++.h>
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);
}
Java
import java.util.*;
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);
}
}
Python
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)
C#
using System;
using System.Collections.Generic;
class Program {
/* 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);
}
}
JavaScript
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() + ' ');
}
}
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);
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.
Using Doubly Ended Queue - O(n+k) Time and O(k) Space
The idea is to use the deque as a temporary container to store the first k elements of the queue and then add them to the queue in reverse order.
Dequeue the first k elements of the queue and push them onto a deque using the push_front() function. Now, Pop the elements from the deque one by one using the pop_front() function and enqueue them back into the queue. Then, Dequeue the remaining elements from the queue and enqueue them back into the queue.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to reverse first k element of the queue
void reverseFirstK(queue<int>& q, int k)
{
deque<int> d;
// Dequeue the first k elements of the queue and push
// them onto a deque
for (int i = 0; i < k; i++) {
d.push_front(q.front());
q.pop();
}
// Pop the elements from the deque and enqueue them back
// into the queue
while (!d.empty()) {
q.push(d.front());
d.pop_front();
}
// Dequeue the remaining elements from the queue and
// enqueue them back into the queue
for (int i = 0; i < q.size() - k; i++) {
q.push(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);
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
return 0;
}
Java
import java.util.*;
public class ReverseFirstKQueue {
// Function to reverse first k elements of the queue
public static void reverseFirstK(Queue<Integer> q, int k){
Deque<Integer> d = new ArrayDeque<>();
// Dequeue the first k elements of the queue and
// push them onto a deque
for (int i = 0; i < k; i++) {
d.push(q.poll());
}
// Pop the elements from the deque and enqueue them
// back into the queue
while (!d.isEmpty()) {
q.add(d.pop());
}
// Dequeue the remaining elements from the queue and
// enqueue them back into the queue
for (int i = 0; i < q.size() - k; i++) {
q.add(q.poll());
}
}
public static void main(String[] args){
Queue<Integer> q = new LinkedList<Integer>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
q.add(5);
int k = 3;
reverseFirstK(q, k);
while (!q.isEmpty()) {
System.out.print(q.peek() + " ");
q.poll();
}
}
}
Python
from collections import deque
def reverseFirstK(q, k):
d = deque()
# Dequeue the first k elements of the queue and push
# them onto a deque
for i in range(k):
d.appendleft(q.popleft())
# Pop the elements from the deque and enqueue them back
# into the queue
while d:
q.append(d.popleft())
# Dequeue the remaining elements from the queue and
# enqueue them back into the queue
for i in range(len(q) - k):
q.append(q.popleft())
q = deque()
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
k = 3
reverseFirstK(q, k)
print(*q)
C#
using System;
using System.Collections.Generic;
public class ReverseFirstKQueue {
// Function to reverse first k elements of the queue
public static void reverseFirstK(Queue<int> q, int k){
Stack<int> s = new Stack<int>();
// Dequeue the first k elements of the queue and
// push them onto a stack
for (int i = 0; i < k; i++) {
s.Push(q.Dequeue());
}
// Pop the elements from the stack and enqueue them
// back into the queue
while (s.Count > 0) {
q.Enqueue(s.Pop());
}
// Dequeue the remaining elements from the queue and
// enqueue them back into the queue
for (int i = 0; i < q.Count - k; i++) {
q.Enqueue(q.Dequeue());
}
}
public 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);
while (q.Count > 0) {
Console.Write(q.Peek() + " ");
q.Dequeue();
}
}
}
JavaScript
// Javascript program to reverse first
// k elements of a queue using dequeue.
function reverseFirstK(q, k) {
const d = [];
// Dequeue the first k elements of the queue and push
// them onto a deque
for (let i = 0; i < k; i++) {
d.unshift(q.shift());
}
// Pop the elements from the deque and enqueue them back
// into the queue
while (d.length !== 0) {
q.push(d.shift());
}
// Dequeue the remaining elements from the queue and
// enqueue them back into the queue
for (let i = 0; i < q.length - k; i++) {
q.push(q.shift());
}
}
const q = [];
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
const k = 3;
reverseFirstK(q, k);
console.log(q.join(' '));
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 deque and then added back to the queue from the deque after that first 'n-k' elements are emptied and enqueued back to the queue.
Auxiliary Space: O(k) , due to the deque used to store the first k elements of the queue.
Reverse First K elements of Queue | DSA Problem
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem