2dbi

Reverse First K Elements of a Queue

viaLeetCode

Problem Reverse the order of the first k elements of a queue, leaving the remaining elements in their original relative order.

Input / Output

  • Input: queue, int k. Output: the queue rearranged in place (logically).

Constraints

  • 1 <= k <= queue size; only standard queue/stack operations allowed — no random access.

Example

  • queue = [1,2,3,4,5], k = 3 → [3,2,1,4,5].

Expected approach

  • Stack for the first k: dequeue k elements pushing onto a stack; pop all back into the queue (now reversed but positioned last); rotate the remaining n−k elements from front to back to restore order. O(n) time, O(k) space. Get the operation count right (n−k rotations, not k). Recursive variant reverses via call stack. Follow-ons: reverse the whole queue, reverse in k-sized chunks (interleave with the same primitives).
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account