Turn the Queue Around
At the canteen the students standing in line are noted down by their roll numbers, front of the queue first. The manager decides that today the last person will be served first, so the whole queue has to be written down in the opposite order.
Return the same roll numbers with the order reversed.
Examples
Example 1
Input: queue = [4, 9, 1, 7]
Output: [7, 1, 9, 4]
The queue is 4, 9, 1, 7. Swapping the ends gives 7, 9, 1, 4; swapping the middle pair gives 7, 1, 9, 4. That is the queue served from the back, so the answer is [7, 1, 9, 4].
Example 2
Input: queue = [3]
Output: [3]
Example 3
Input: queue = [1, 2]
Output: [2, 1]
Constraints
queue has 1 to 10,000 roll numbers. You may return a new array or change the given one and return it.
The returned array must hold exactly the same numbers, from the last one to the first one.
How to solve it
Hint
Swap the ends, then the next pair inwards, until the two ends meet in the middle.
Approach: Two pointers · in-place reverse
- Put one index at the start and one at the end.
- Swap the two values, then move the left index right and the right index left.
- Stop when they meet, and return the array.
Check with the example. [4, 9, 1, 7] swaps 4 with 7 and 9 with 1, giving [7, 1, 9, 4].
Complexity: O(n) time, O(1) extra space.
The reference solutions in all four languages are in the Solutions tab of the workspace below.
Item 5 of 90 · updated 2026-10-12