Rotate Array

Medium

Topics
ArrayTwo Pointers

Given an array nums, rotate it to the right by k steps (k passed as target) and return the rotated array.

Example 1

before1234567
after5671234
Rotating right by 3 moves the shaded tail to the front; the effective shift is k % 7 = 3. The in-place method is three reversals — reverse the whole array, then each of the two parts — which needs no extra buffer.
Top row is the input; below it the rotated result.
Input:  nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]

Example 2

before-1-100399
after399-1-100
Input:  nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= k <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

Rotating right by k moves the last k elements to the front. Reduce k modulo n first (rotating by n does nothing).

The elegant in-place trick: reverse the whole array, then reverse the first k and the remaining n-k — O(1) space.

Approach

  1. Set k %= n.
  2. Reverse the entire array.
  3. Reverse the first k elements, then reverse the rest.

Walkthrough

nums=[1,2,3,4,5,6,7], k=3
reverse all -> [7,6,5,4,3,2,1]
reverse first 3 -> [5,6,7,4,3,2,1]
reverse rest -> [5,6,7,1,2,3,4]

Complexity

  • Time — O(n): the reversals touch each element a constant number of times.
  • Space — O(1): the reversal method rotates in place.

Common Pitfalls

  • Reduce k modulo n, or large k breaks slicing / over-rotates.

Full Solution — all languages

class Solution:
    def rotate(self, nums, target):
        n = len(nums)
        if n == 0:
            return nums
        k = target % n
        return nums[n - k:] + nums[:n - k]
SensAI
Beta
Tap the mic to stop voice mode