The problem. Given an array nums, rotate it to the right by k steps, where k is non-negative. One step moves the last element to the front. Do it in place with O(1) extra space.
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Input: nums = [-1, -100, 3, 99], k = 2
Output: [3, 99, -1, -100]Rotating right by k means the last `k` elements move to the front, in the same order, and everything else shifts right by k.
Rotating by the array's length n puts every element back where it started. So rotating by k is the same as rotating by k % n — with n = 7 and k = 10, only 3 steps actually matter. Always reduce k first.
Free account
Sign up to read the rest of this lesson: 5 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come