Given an array representing a deque (double-ended queue), reverse the order of its elements and return the reversed array. Reversing a deque means the front becomes the back and vice versa.
For example, reversing [1, 2, 3] produces [3, 2, 1]. An empty deque reversed is still empty. A single-element deque [5] reversed is [5]. Reversing [10, 20, 30, 40] produces [40, 30, 20, 10].
Reversing a deque is useful when you need to change the processing order. For example, if items were added in reverse priority order, reversing the deque re-establishes the correct priority. This operation is related to the stack-based reversal pattern and can be implemented using a temporary stack or two-pointer swap.
In array-based deque implementations, reversal can be done by swapping elements from both ends moving inward (two-pointer technique), or by using a built-in reverse method. In linked-list-based deques, reversal requires updating the next and previous pointers of every node.
Edge cases include an empty deque (return []), a single-element deque (return the same), and a two-element deque (simple swap). The reversal preserves all element values and only changes their order.
Example Input & Output
Three elements
Two elements
Reverse order
Single
Empty
Algorithm Flow
Solution Approach
Reverse the array using the two-pointer swap technique or a built-in reverse method.
Create a copy of the array, then use two pointers (i at start, j at end) to swap elements inward until they meet. Alternatively, use the built-in reverse method: arr.slice().reverse(). The two-pointer approach demonstrates the underlying algorithm.
Time complexity is O(n), space complexity is O(n) for the copy or O(1) for in-place reversal.
Best Answers
class Solution {
public int[] solution(int[] nums) {
int n=nums.length;int[] r=new int[n];
for(int i=0;i<n;i++)r[i]=nums[n-1-i];
return r;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
