Reverse the first K elements of a queue

Easy

Problem

Reverse the order of the first k elements of a queue and leave the rest in their original order.

Example 1

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

Also asked as: Reverse the first “K” elements of a queue

Test cases

Case 1

Input:    [1,2,3,4,5], 3
Expected: [3,2,1,4,5]

Case 2

Input:    [1,2,3], 3
Expected: [3,2,1]

Case 3

Input:    [1,2,3], 1
Expected: [1,2,3]

Case 4

Input:    [1,2], 0
Expected: [1,2]

Your solution ✓ Solved

Ctrl/⌘ + Enter to run
View solutionHide solution1 approach

1. Stack for the first K, then rotate the rest

Time O(n)Space O(k)

Dequeue K into a stack, enqueue them back (reversed), then move the remaining n−K elements from front to back.

function reverseFirstK(queue, k) {
const st = [];
for (let i = 0; i < k; i++) st.push(queue.shift());
while (st.length) queue.push(st.pop());
for (let i = 0; i < queue.length - k; i++) queue.push(queue.shift());
return queue;
}