Rotate Array
Medium
Topics
Given an array nums, rotate it to the right by k steps (k passed as target) and return the rotated array.
Example 1
before
after
Rotating right by 3 moves the shaded tail to the front; the effective shift is
k % 7 = 3. The in-place method is three reversals — reverse the whole array, then each of the two parts — which needs no extra buffer.Top row is the input; below it the rotated result.
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Example 2
before
after
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100]
Constraints
- 1 <= nums.length <= 10^5
- 0 <= k <= 10^5
Editorial — intuition, approach, complexity and pitfalls
Intuition
Rotating right by k moves the last k elements to the front. Reduce k modulo n first (rotating by n does nothing).
The elegant in-place trick: reverse the whole array, then reverse the first k and the remaining n-k — O(1) space.
Approach
- Set
k %= n. - Reverse the entire array.
- Reverse the first
kelements, then reverse the rest.
Walkthrough
nums=[1,2,3,4,5,6,7], k=3
reverse all -> [7,6,5,4,3,2,1]
reverse first 3 -> [5,6,7,4,3,2,1]
reverse rest -> [5,6,7,1,2,3,4]Complexity
- Time — O(n): the reversals touch each element a constant number of times.
- Space — O(1): the reversal method rotates in place.
Common Pitfalls
- Reduce
kmodulon, or largekbreaks slicing / over-rotates.
Full Solution — all languages
class Solution:
def rotate(self, nums, target):
n = len(nums)
if n == 0:
return nums
k = target % n
return nums[n - k:] + nums[:n - k]import java.util.*;
class Solution {
public int[] rotate(int[] nums, int target) {
int n = nums.length;
int[] r = new int[n];
int k = n == 0 ? 0 : target % n;
for (int i = 0; i < n; i++) r[(i + k) % n] = nums[i];
return r;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> rotate(vector<int>& nums, int target) {
int n = (int)nums.size();
vector<int> r(n);
int k = n == 0 ? 0 : target % n;
for (int i = 0; i < n; i++) r[(i + k) % n] = nums[i];
return r;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/ var rotate = function(nums, target) {
const n = nums.length;
const r = new Array(n);
const k = n === 0 ? 0 : target % n;
for (let i = 0; i < n; i++) r[(i + k) % n] = nums[i];
return r;
};