Rotate Array

medium

Given an integer array arr and a positive integer d, left-rotate (counter-clockwise) the array by d steps and return the result.

A left rotation by one step moves every element one slot toward the front; the element that falls off the front wraps around to the back. Doing this d times, the element at index i ends up at index (i - d) mod n — equivalently, the result at index i is the original arr[(i + d) mod n].

Treat the array as circular, and note that d may be larger than the length: rotating by n leaves the array unchanged, so a rotation by d is the same as a rotation by d mod n. For example, arr = [1, 2, 3, 4, 5] with d = 2 becomes [3, 4, 5, 1, 2].

Hints

Rotating left by d sends the element at index i to index (i - d) mod n. Equivalently, the result at index i is the original arr[(i + d) mod n].
d can be far bigger than n. Since rotating by n changes nothing, first reduce d to d mod n.
For O(1) extra space, think in reversals: reverse the first d elements, reverse the rest, then reverse the whole array — and watch it snap into place.

Common doubts

After d mod n the rotation amount is 0, so the array is unchanged. Both approaches handle this automatically.
Left (counter-clockwise): [1,2,3,4,5] by 2 gives [3,4,5,1,2]. A right rotation would give [4,5,1,2,3].
Any correct output is accepted, but the interesting challenge — and what an interviewer pushes on — is doing it in O(1) extra space with the three-reversal trick.

Interview follow-ups

Yes — the three-reversal method rotates in place in O(n) time and O(1) space.
A right rotation by d equals a left rotation by n - (d mod n), so the same reversal trick applies.

Fun facts

  • The three-reversal identity — reverse(A) + reverse(B) reversed equals B + A — is the same block-swap trick used in in-place string rotation and the classic 'rotate the words in a sentence' problem.
  • Rotations power circular buffers and round-robin schedulers, where the array is conceptually endless and indices wrap with mod.

Asked at

AmazonMicrosoftAdobeGoogle
Frequently Sometimes Occasionally
Example 1
Input: arr = [1, 2, 3, 4, 5], d = 2
Output: [3, 4, 5, 1, 2]
Each element shifts 2 places left; the first 2 wrap to the end.
Example 2
Input: arr = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20], d = 3
Output: [8, 10, 12, 14, 16, 18, 20, 2, 4, 6]
The first 3 elements move to the back after a 3-step left rotation.
Example 3
Input: arr = [7, 3, 9, 1], d = 9
Output: [3, 9, 1, 7]
d is larger than the length: 9 mod 4 = 1, so this is a single left rotation.
Constraints

- 1 <= arr.size <= 10^5 - 1 <= d <= 10^5 - 0 <= arr[i] <= 10^5

Solve this problem →