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
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem