loading

Rotate Array — Step-by-Step Visualization

mediumLeetCode #189ArrayMathTwo Pointers

Given an integer array nums, rotate the array to the right by k steps, where k is non-negative.

Algorithm Pattern

Three Reverses

Key Idea

Rotating right by k = reverse all, then reverse first k, then reverse rest.

Step-by-Step Approach

  1. k = k % n
  2. Reverse entire array
  3. Reverse nums[0..k-1]
  4. Reverse nums[k..n-1]

Related Problems