AceYourInterviews
Checking sign-in…

8. Rotate Array

IntermediateIn-place rotation by reversal

Move each array value k positions to the right, wrapping values that pass the end back to the beginning. Perform the rearrangement in the original array rather than returning a replacement.

Rotation amounts can exceed the array length. The contract explains how to normalize k and handle boundary inputs without losing or duplicating values.

Example 1

Input

nums=[1,2,3,4,5,6,7], k=3

Output

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

Explanation: The last three positions move to the front without reversing either block’s final order.

Example 2

Input

nums=[1,2,3], k=4

Output

nums becomes [3,1,2]

Explanation: Four right steps are equivalent to one because k mod 3 is one.

Constraints

  • 0 <= nums.length <= 105
  • -231 <= nums[i] <= 231 - 1
  • 0 <= k <= 263 - 1
Hints
Hint 1

Describe a right rotation as moving a suffix before a prefix.

Hint 2

What order does reversing the whole concatenation produce?

Hint 3

Reverse the whole array, then each of its two new blocks.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Restore both reversed blocks

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