Code Logo

Deque Reverse

Published at25 Jul 2026
Deque Easy 1 views
Like0

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

Example 1
Input
[10,20,30]
Output
[30,20,10]
Explanation

Three elements

Example 2
Input
[1,2]
Output
[2,1]
Explanation

Two elements

Example 3
Input
[1,2,3,4,5]
Output
[5,4,3,2,1]
Explanation

Reverse order

Example 4
Input
[1]
Output
[1]
Explanation

Single

Example 5
Input
[]
Output
[]
Explanation

Empty

Algorithm Flow

Recommendation Algorithm Flow for Deque Reverse

Solution Approach

Reverse the array using the two-pointer swap technique or a built-in reverse method.

function solution(arr) {
  var r = arr.slice();
  for (var i = 0, j = r.length - 1; i < j; i++, j--) {
    var t = r[i]; r[i] = r[j]; r[j] = t;
  }
  return r;
}

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

java
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;
    }
}