Reversing the first K of a Queue

Last Updated : 27 Jul, 2026

Given an integer k and a queueq 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.

Note: If the size of queue is smaller than the given k , then return the original queue.

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].

Try It Yourself
redirect icon

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.
C++
#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) {
    
    if(k > q.size())return q;
    
    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.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) {
       
       if(k > q.size()) return q; 
       
       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 reverseFirstK(q, k):
    
    if k > len(q):
        return q;
    moveKToEnd(q, k)
    s = len(q) - k
    for _ in range(s):
        x = q.popleft()
        q.append(x)
    return q

def moveKToEnd(q, k):
    if k == 0:
        return
    e = q.popleft()
    moveKToEnd(q, k - 1)
    q.append(e)

if __name__ == "__main__":
    queue = deque([1, 2, 3, 4, 5])
    k = 3
    queue = reverseFirstK(queue, k)
    
    while queue:
        print(queue.popleft(), end=' ')
C#
using System;
using System.Collections.Generic;

class GFG {
    
    static Queue<int> reverseFirstK(Queue<int> q, int k) {
        
        if (k > q.Count) return q;
        
        moveKToEnd(q, k);
        
        int s = q.Count - k;
        while (s > 0) {
            int x = q.Dequeue();
            q.Enqueue(x);
            s = s - 1;
        }
        
        return q;
    }
    
    static void moveKToEnd(Queue<int> q, int k) {
        if (k == 0) {
            return;
        }
        
        int e = q.Dequeue();
        moveKToEnd(q, k - 1);
        q.Enqueue(e);
    }

    public static void Main(string[] args) {
        
        Queue<int> q = new Queue<int>();
        q.Enqueue(1);
        q.Enqueue(2);
        q.Enqueue(3);
        q.Enqueue(4);
        q.Enqueue(5);
        
        int k = 3;
    
        q = reverseFirstK(q, k);
        
        while (q.Count > 0) {
            Console.Write(q.Dequeue() + " ");
        }
    }
}
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(q, k) {

    if(k > q.size()) return q;
    moveKToEnd(q, k);

    let s = q.size() - k;
    while (s-- > 0) {
        let x = q.front();
        q.pop();
        q.push(x);
    }

    return q;
}

function moveKToEnd(q, k) {
    if (k == 0)
        return;

    let e = q.front();
    q.pop();

    moveKToEnd(q, k - 1);

    q.push(e);
}

// Driver code
let q = new Queue();
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);

let k = 3;
q = reverseFirstK(q, k);

// Printing queue
while (!q.isEmpty()) {
    console.log(q.front());
    q.pop();
}

Output
3 2 1 4 5 

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.
C++
#include <iostream>
#include<vector>
using namespace std;

// Function to reverse the first
//   K elements of the Queue 
queue<int> reverseFirstK(queue<int>& q, int k)
{
    if (q.empty() == true || k > q.size())
        return q;
    if (k <= 0)
        return q;

    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();
    }
    
    return q;
}

// 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;
    queue<int> res = reverseFirstK(q, k);
    Print(res);
}
Java
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 Queue<Integer> reverseFirstK(Queue<Integer> q, int k) {
        if (q.isEmpty() || k > q.size())
            return q;
        if (k <= 0)
            return q;

        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());
        }
        
        return q;
    }

    // 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;
        Queue<Integer> res = reverseFirstK(q, k);
        print(res);
    }
}
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 q
    if k <= 0:
        return q

    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())
    return q

# 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
    res = reverseFirstK(q, k)
    printQueue(res)
C#
using System;
using System.Collections.Generic;

class GFG {
    
    // Function to reverse the first
    //   K elements of the Queue 
    static Queue<int> reverseFirstK(Queue<int> q, int k) {
        if (q.Count == 0 || k > q.Count)
            return q;
        if (k <= 0)
            return q;

        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());
        }
        
        return q;
    }

    // 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;
        Queue<int> res = reverseFirstK(q, k);
        Print(q);
    }
}
JavaScript
function reverseFirstK(q, k) {
    if (q.length === 0 || k > q.length)
        return q;
    if (k <= 0)
        return q;

    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());
    }
    
    return q;
}

// 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;
res = reverseFirstK(q, k);
printQueue(res);

Output
3 2 1 4 5 
Comment