v9.1.1
Menu

Rotate Array

easyPROArrays & SortingAmazon DSA

Given an integer array nums, rotate the array to the right by k steps.

Implement rotate(nums, k) so that it modifies nums in place and returns nothing; the tests print nums after the call as space-separated integers.

k may be larger than the length of nums.

Example

Input
1,2,3,4,5,6,7
3
Output
5 6 7 1 2 3 4
Reasoning
  • nums is the array 1,2,3,4,5,6,71, 2, 3, 4, 5, 6, 7 with n=7n = 7 elements, and k=3k = 3 is how many positions every element shifts to the right.
  • One step right moves each element up one index, and the one falling off the end wraps to index 00. After kk steps, the element at index ii lands at index (i+k) mod n(i + k) \bmod n.
  • Work it through: 11 at index 00 goes to index 33; 44 at index 33 goes to index 66; 55 at index 44 goes to (4+3) mod 7=0(4+3) \bmod 7 = 0; 77 at index 66 goes to 9 mod 7=29 \bmod 7 = 2.
  • Reading the new positions 00 to 66 gives 5 6 7 1 2 3 4: the last three values now lead, and the first four keep their relative order behind them.
  • Notice that rotating by n=7n = 7 returns every element to where it started, so k=10k = 10 gives the same result as k=3k = 3, and k=0k = 0 leaves the array unchanged.

Constraints

  • 1 <= len(nums) <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 10^5

More from Amazon DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.