0% found this document useful (0 votes)
35 views8 pages

Reverse First K Elements of A Queue

Uploaded by

lonesome.rar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views8 pages

Reverse First K Elements of A Queue

Uploaded by

lonesome.rar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

1/2/25, 12:15 PM Reverse First K Elements Of A Queue

AfterAcademy

Admin AfterAcademy
5 Oct 2020

Reverse First K Elements Of a Queue

Difficulty: Medium

Understanding The Problem


Problem Description

Given an integer k and queue Q of integers. Write a program to reverse


the order of the first k elements of the queue. The other elements will be

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 1/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

in the same relative order. The following standard operations are allowed
on the queue:

enqueue(x) : Insert an item x to the rear of queue

dequeue() : Remove an item from the front of queue

size() : Returns the number of items in the queue.

peek() : Get the front item.

empty() : Return whether the queue is empty.

Example 1

Input: Q = [1, 2, 3, 4, 5]
k = 5
Output: Q = [5, 4, 3, 2, 1]
Explanation: The first 5 elements of Q are reversed.

Example 2

Input: Q = [1, 2, 3, 4, 5, 6]
k = 4
Output: Q = [4, 3, 2, 1, 5, 6]
Explanation: The first 4 elements of Q are reversed.

Solution
The problem asked us to reverse the first K elements of the queue and we
can use the predefined operations given above. To reverse some segment of
the queue, we can use an auxiliary stack (How?).

If we insert all the elements of the queue in a stack using the dequeue
operation, then we will have a stack that will be seen reversed of the queue.

For example, If we have a queue of numbers sorted in ascending order, then


inserting all elements of the queue into a stack one by one, then the top of
https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 2/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

the resultant stack will have the smallest element, i.e. the stack will be in
descending order. We can use this concept here.

We will take an auxiliary empty stack. We will dequeue the first K


elements of the queue and push them into the stack one by one. Now, we
will pop all elements of the stack and enqueue into the queue one by one. In
this way, we will have the input queue with the first K elements in the
reversed order at the rear of the queue. We will dequeue (size — k)
elements from the front and enqueue in the same queue one by one. Thus,
we will have the resultant queue with the first K elements in reversed order.

Look at the below example for clear understanding, Here queue is given to
you and K is 4:

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 3/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

Solution Steps
https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 4/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

1. Create an empty stack.

2. Dequeue K items from the queue and push them into the stack, one by
one.

3. Enqueue the contents of the stack at the back of the queue

4. Dequeue (size-k) elements from the front and enqueue them one by
one in the same queue.

Pseudo Code

int[] reverseQueueFirstKElements(queue Q, int k) {


if (queue is Empty or k > queue.size())
return Q
Stack stack
for (int i = 0 to i < k) {
stack.push(queue.peek())
queue.dequeue()
}
while (stack is not empty()) {
queue.enqueue(stack.top())
stack.pop()
}
for (int i = 0 to i < queue.size() - k) {
queue.enqueue(queue.peek())
queue.dequeue()
}
return queue
}

Complexity Analysis

Time Complexity: O(n+k)

Where n is the queue size and k is the number of elements to be reversed.

Space Complexity: O(n)

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 5/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

Critical Ideas To Think

How did we rotate the first K elements?

Can we solve this problem by using two auxiliary queues instead of one
auxiliary stack?

Why did we enqueue the items from the same queue in the last loop?
And why such operation is performed for size — k times only?

Suggested Problems To Solve


Reversing a Queue using another Queue

Reversing a queue using recursion

Check if a queue can be sorted into another queue using a stack

Queue based approach for the first non-repeating character in a stream

Reverse a stack using a queue.

Please comment down below if you have a better insight in the above approach.

Happy Coding, Enjoy Algorithms!

Recommended for You

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 6/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

Reverse a Stack Using Surrounded regions


Recursion Given a 2-D matrix board where every
Given a stack of integers st, write a program element is either 'O' or 'X', write a program to
to reverse the stack using recursion. This replace 'O' with 'X' if surrounded by 'X'. It is a
problem will clear the concept of recursion. famous problem based on the concept of
Admin AfterAcademy flood fill algorithms
Admin AfterAcademy
6 Oct 2020 23 Sep 2020

Largest Element In An Array Merge Two BST


Given an array arr[] of size n , write a Given two binary search trees with root
program to find the largest element in it. To nodes as tree1 and tree2 of size n and m,
find the largest element we can just traverse write a program to return an array of
the array in one pass and find the largest integers that contains all the elements of
element by maintaining a max variable. tree1 and tree2 in non-decreasing order. The
expected time complexity is O(m+n).

Admin AfterAcademy Admin AfterAcademy


4 Sep 2020 1 Sep 2020

Wave Array Reverse Bits


You are given an unsorted array of
integers(arr) of length n, write a program to
sort it in wave form. The array elements in

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 7/8
1/2/25, 12:15 PM Reverse First K Elements Of A Queue

the resultant array must be such that arr[0] Given a non-negative integer num, write a
>= arr[1] <= arr[2] >= arr[3] <= arr[4] ... and so program to return the number obtained after
on. If there are multiple sorted orders in reversing the bits of num.
wave-form, return the one which is
lexicographically smallest.
Admin AfterAcademy Admin AfterAcademy
20 Aug 2020 15 Aug 2020

Connect With Your Mentors

Janishar Ali Amit Shekhar


Founder | IIT-BHU | 10 Yrs Exp. Founder | IIT-BHU | 10 Yrs Exp.

Copyright 2022, MindOrks Nextgen Private Limited

https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 8/8

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy