AlgoFrames

Rotate by k

Standard · Write code · about 12 min

Rotate nums to the right by k steps and return it. After one step the last value moves to the front: [1, 2, 3] becomes [3, 1, 2].

k can be larger than the length. Aim for O(n) time and O(1) extra space.

Example 1

Input:

[[1,2,3,4,5,6,7],3]

Output:

[5,6,7,1,2,3,4]

Example 2

Input:

[[1,2],5]

Output:

[2,1]

5 mod 2 = 1, so this is a rotation by 1.

Constraints

  • 0 ≤ nums.length ≤ 10,000
  • 0 ≤ k ≤ 100,000
  • -10,000 ≤ nums[i] ≤ 10,000

Learn the idea first: Arrays: indexing, traversal, insertion and deletion costs, a visual lesson.

More Arrays: indexing, traversal, insertion and deletion costs problems