175/670

175. Rotate Array

Medium

You have an integer array nums and a non-negative integer k. Cycle the array’s contents k steps toward the back: a single step slides every element into the next-higher index and carries the final element around to index 0, and you repeat that shift k times.

The rotation must happen in place — the function mutates nums and returns nothing. Note that k may be larger than the array length, in which case rotating by k is the same as rotating by k mod n.

Copying everything into a second array works, but the interesting version of this problem keeps the extra memory down to O(1).

Rotate right by k with three reversals
start: [1 2 3 4 5 6 7], k=312345671. reverse whole array76543212. reverse first k | 3. reverse rest5671234

Example 1:

Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3

Output: nums becomes [5, 6, 7, 1, 2, 3, 4]

Explanation: The last three elements 5, 6, 7 wrap to the front; everything else shifts right by three.

Example 2:

Input: nums = [-1, -100, 3, 99], k = 2

Output: nums becomes [3, 99, -1, -100]

Explanation: Rotating right by 2 brings the final pair 3, 99 to the front.

Constraints:

  • 0 ≤ nums.length ≤ 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • 0 ≤ k ≤ 10⁹

Hints:

First reduce k: rotating right by k is the same as rotating by k mod n, and if n is 0 there is nothing to do.

One clean O(1)-space trick uses reversals. Reverse the whole array, then reverse the first k elements, then reverse the remaining n - k.

Convince yourself with a small example why three reversals leave each element in its rotated position.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3

Expected output: [5, 6, 7, 1, 2, 3, 4]