Code Logo

Deque Rotate

Published at25 Jul 2026
Deque Easy 2 views
Like0

Given an array representing a deque (double-ended queue) and an integer k, rotate the elements to the LEFT by k positions. A left rotation shifts each element k positions toward the front, with the first k elements wrapping around to the back. The cyclic order of the elements is preserved.

For example, rotating [1, 2, 3] left by 1 produces [2, 3, 1]. Rotating [1, 2, 3, 4, 5] left by 2 produces [3, 4, 5, 1, 2]. Rotating by 0 returns the array unchanged. Rotating a single-element array by any amount returns that element. An empty array rotated by any amount stays empty.

Rotation is a fundamental operation on circular data structures. It models shifting elements in a ring buffer, rotating a rotating shift schedule, or cycling through a playlist. In a deque, rotating left is equivalent to repeatedly popping the front and pushing it to the back.

The simplest approach slices the array at index k: the result is arr[k:] concatenated with arr[:k]. The value of k should first be reduced modulo the array length so that rotating by more than the length produces the same result as rotating by the remainder. For example, rotating [1, 2, 3] by 4 is the same as rotating by 1.

Edge cases include k=0 (return the array unchanged), k a multiple of the length (return unchanged after the modulo), k larger than the length (apply k % n first), an empty array (return an empty array), and a single-element array (return the same single element).

Example Input & Output

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

Single element

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

Rotate left by 1

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

Rotate left by 2

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

No rotation

Example 5
Input
[],5
Output
[]
Explanation

Empty

Algorithm Flow

Recommendation Algorithm Flow for Deque Rotate

Solution Approach

Rotate the array to the left by slicing at index k and concatenating the two parts in swapped order. First normalize k with the modulo operator so that k is always in the range [0, n-1]. Then the result is arr.slice(k).concat(arr.slice(0, k)) — the elements from k to the end come first, followed by the elements from 0 to k-1.

function solution(arr, k) {
  if (arr.length === 0) return [];
  k = k % arr.length;
  return arr.slice(k).concat(arr.slice(0, k));
}

The modulo operation makes rotating by more than the length equivalent to rotating by the remainder. For example, rotating [1, 2, 3] by 4 reduces to rotating by 1, producing [2, 3, 1].

Time O(n), Space O(n).

Best Answers

java
class Solution {
    public int[] solution(int[] nums, int k) {
        int n=nums.length;if(n==0)return new int[]{};k%=n;
        int[] r=new int[n];
        for(int i=0;i<n;i++)r[i]=nums[(i+k)%n];
        return r;
    }
}