Rotate Array
Module 4 · Arrays & Dynamic Arrays
Problem
Given an integer array nums, rotate it right by k steps, in place.
Examples
Example 1
Input
nums = [1,2,3,4,5,6,7], k = 3Output[5,6,7,1,2,3,4]Example 2
Input
nums = [-1,-100,3,99], k = 2Output[3,99,-1,-100]Constraints
1 ≤ n ≤ 10⁵ · 0 ≤ k ≤ 10⁵ (note: k can exceed n!) · follow-up: O(1) auxiliary space.
Attempt it first
The O(n)-space version is warm-up; get it working mentally first. The real problem is O(1) space — and the trick is not an incremental shuffle.
Note the constraint: k can exceed n, so normalise it before you index anything.