Description

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. Elements that shift off the right end wrap around to the left end.

Examples

Input:nums = [1,2,3,4,5,6,7], k = 3
Output:[5,6,7,1,2,3,4]
Explanation:

Rotate 1 step: [7,1,2,3,4,5,6], rotate 2 steps: [6,7,1,2,3,4,5], rotate 3 steps: [5,6,7,1,2,3,4]

Input:nums = [-1,-100,3,99], k = 2
Output:[3,99,-1,-100]
Explanation:

Rotate 2 steps to the right.

Input:nums = [10,20,30], k = 5
Output:[20,30,10]
Explanation:

When k is larger than the array length, only need to rotate k % length times. Since k=5 and length=3, rotating 5%3=2 steps: rotate 1 step: [30,10,20], rotate 2 steps: [20,30,10]

Constraints

  • 1 ≤ nums.length ≤ 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • 0 ≤ k ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!