Reverse First K Elements of A Queue
Reverse First K Elements of A Queue
AfterAcademy
Admin AfterAcademy
5 Oct 2020
Difficulty: Medium
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:
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.
the resultant stack will have the smallest element, i.e. the stack will be in
descending order. We can use this concept here.
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
2. Dequeue K items from the queue and push them into the stack, one by
one.
4. Dequeue (size-k) elements from the front and enqueue them one by
one in the same queue.
Pseudo Code
Complexity Analysis
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
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?
Please comment down below if you have a better insight in the above approach.
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
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
https://afteracademy.com/blog/reverse-first-k-elements-of-a-queue/ 8/8