Coding problem · Easy · Basics
Rotate an Array
Easy Algorithms & data structures
Return nums rotated to the right by k steps: the last k elements move to the front. k may be larger than the array's length.
Example 1
Input: nums = [1,2,3,4,5], k = 2 Output: [4,5,1,2,3]
Example 2
Input: nums = [1,2], k = 3 Output: [2,1] Explanation: Rotating by 3 is the same as rotating by 1.
Hints
Hint 1
Rotating by the array's length gives the same array, so use k % n.
Hint 2
The answer is the last k elements followed by the rest.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(n)
Normalise k = k % n, then concatenate the last k elements with the first n - k. (An in-place version reverses the whole array, then each part.)
Reference solution
function rotateRight(nums, k) {
const n = nums.length;
if (n === 0) return [];
k %= n;
return [...nums.slice(n - k), ...nums.slice(0, n - k)];
}
function rotateRight(nums: number[], k: number): number[] {
const n = nums.length;
if (n === 0) return [];
k %= n;
return [...nums.slice(n - k), ...nums.slice(0, n - k)];
}
def rotate_right(nums: list[int], k: int) -> list[int]:
if not nums:
return []
k %= len(nums)
return nums[-k:] + nums[:-k] if k else nums[:]
<?php
function rotateRight(array $nums, int $k): array
{
$n = count($nums);
if ($n === 0) {
return [];
}
$k %= $n;
return array_merge(array_slice($nums, $n - $k), array_slice($nums, 0, $n - $k));
}
class Solution {
public int[] rotateRight(int[] nums, int k) {
int n = nums.length;
int[] out = new int[n];
for (int i = 0; i < n; i++) out[(i + k) % n] = nums[i];
return out;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy