Magicsheet logo

Rotate Array

Medium
84%
Updated 6/1/2025

Rotate Array

What is this problem about?

The Rotate Array interview question asks you to rotate an integer array to the right by k steps in-place, using O(1) extra space. Rotating right by k means the last k elements move to the front, and the remaining elements shift right. For example, rotating [1,2,3,4,5] by 2 gives [4,5,1,2,3].

Why is this asked in interviews?

This problem is asked at Apple, Samsung, Uber, Goldman Sachs, Microsoft, Meta, Amazon, Google, Bloomberg, and Adobe because it has multiple solutions of increasing elegance — brute force, extra array, cyclic replacement, and the elegant triple-reversal technique. It tests in-place manipulation, modular arithmetic for handling k > n, and understanding the relationship between rotation and reversal.

Algorithmic pattern used

The most elegant pattern is the triple reversal: (1) reverse the entire array, (2) reverse the first k elements, (3) reverse the remaining n-k elements. Always reduce k to k % n first to handle cases where k ≥ n.

The cyclic replacement pattern is also O(1) space: start at each position, follow the "destination" chain (i + k) % n, placing elements until the cycle completes.

Example explanation

Array: [1, 2, 3, 4, 5, 6, 7], k = 3.

k = 3 % 7 = 3.

Step 1 — Reverse all: [7, 6, 5, 4, 3, 2, 1]. Step 2 — Reverse first 3: [5, 6, 7, 4, 3, 2, 1]. Step 3 — Reverse last 4: [5, 6, 7, 1, 2, 3, 4].

Result: [5, 6, 7, 1, 2, 3, 4]. Correct!

Extra array approach (O(n) space): new_arr[(i+k) % n] = nums[i] for each i. Then copy back.

Common mistakes candidates make

  • Not reducing k modulo n first — if k = n, no rotation is needed.
  • Using extra space when in-place is required.
  • Implementing the triple reversal with wrong subarray boundaries — reverse [0, k-1] and [k, n-1] after the full reversal.
  • In the cyclic approach, not tracking the number of elements placed, causing early termination.

Interview preparation tip

For the Rotate Array coding problem, the array and two-pointer interview pattern via triple reversal is the most interview-friendly approach. Memorize the three reversal steps and the k %= n preprocessing. Interviewers at Netflix and Capital One sometimes ask for all three approaches (brute force, extra array, triple reversal) and ask which is best — triple reversal wins on both time and space complexity. Practice explaining the mathematical intuition: reversing the whole array and then fixing the two halves restores the correct order.

Similar Questions