Queue: Reverse first K elements in the queue

Problem Statement:

You are given a queue and a number k.

You need to reverse the first k elements from the queue.

Example:

Input: 1 2 3 4 5 K = 3

Output: 3 2 1 4 5

Solution : Using stack

For the solution, take a temp stack and dequeue the first k element from the queue and insert them into the stack.

Pop the elements into the stack and add them into the queue.

Now for the remaining elements from the queue,remove the elements from the queue and then add back to the queue

Time Complexity: O(n + k)
Space Complexity: O(k)

Code Solution

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

void reverse(queue<int>& q, int k)
{
    if (q.empty() == true || k > q.size())
        return;

    if (k <= 0)
        return;

    stack<int> s;

    for (int i = 0; i < k; i++) 
    {
        s.push(q.front());
        q.pop();
    }

    while (!s.empty()) 
    {
        q.push(s.top());
        s.pop();
    }


    for (int i = 0; i < q.size() - k; i++) 
    {
        q.push(q.front());
        q.pop();
    }
}

void display(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;
    reverse(q, k);
    display(q);
}

Output

3 2 1 4 5
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *