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)];
}

Was this page helpful?