Rotate Array Right
Medium arrays
Description
Constraints
0 <= n <= 100000; 0 <= k
Examples
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Hints (1)
- Reduce k modulo n; the last k elements move to the front.
Solutions
Split at n-k and swap the halves. · Time O(n) · Space O(n)
func rotateRight(nums []int, k int) []int {
n := len(nums)
if n == 0 {
return []int{}
}
k %= n
out := make([]int, 0, n)
out = append(out, nums[n-k:]...)
out = append(out, nums[:n-k]...)
return out
}
Split at n-k and swap the halves. · Time O(n) · Space O(n)
function rotateRight(nums, k) {
const n = nums.length;
if (n === 0) return [];
k %= n;
return nums.slice(n - k).concat(nums.slice(0, n - k));
}
Split at n-k and swap the halves. · Time O(n) · Space O(n)
function rotateRight($nums, $k) {
$n = count($nums);
if ($n === 0) { return []; }
$k %= $n;
return array_merge(array_slice($nums, $n - $k), array_slice($nums, 0, $n - $k));
}
Split at n-k and swap the halves. · Time O(n) · Space O(n)
def rotateRight(nums, k):
n = len(nums)
if n == 0:
return []
k %= n
return nums[n - k:] + nums[:n - k]
Split at n-k and swap the halves. · Time O(n) · Space O(n)
function rotateRight(nums: number[], k: number): number[] {
const n = nums.length;
if (n === 0) return [];
k %= n;
return nums.slice(n - k).concat(nums.slice(0, n - k));
}
Create a free account to submit solutions, track progress and save problems.
Create account