Queue: Given a queue and element k, revert the first k element of the queue

Problem Statement:

You are given an queue and integer k.

You need to reverse the order of first k element of the queue.

Below are the operations allowed:

1. enqueue

2. dequeue

3. size

4. front

Example:

Input: q = [1, 2, 3, 4, 5], k = 3

Output: 3 2 1 4 5

Solution Explanation:

Steps are simple as below:

1. Push first k the elements into the stack

2. Then enqueue the elements from the stack into queue

3. Move the remaining element to the back

Time Complexity: O(1)
Space Complexity: O(1)

Code Solution

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


void solution(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;

    solution(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 *