Rotate Array
Medium
ArrayTwo PointersMath
Problem
Given an integer array nums, rotate it to the right by k steps. Do it in place with O(1) extra memory.
Example 1
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Example 2
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Constraints
- 1 ≤ length ≤ 10⁵
- 0 ≤ k ≤ 10⁵
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def rotate(self, nums, k):
n = len(nums)
k %= n
nums[:] = nums[-k:] + nums[:-k] if k else nums
return nums
Java
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
reverse(nums, 0, n - 1);
reverse(nums, 0, k - 1);
reverse(nums, k, n - 1);
}
private void reverse(int[] a, int l, int r) {
while (l < r) { int t = a[l]; a[l++] = a[r]; a[r--] = t; }
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Rotate Array interactively → ← All solutions