189. Rotate Array
Asked at 25Apple78Bloomberg64Microsoft62Amazon58Google56Meta50tcs67TikTok56Infosys54Fiverr100Box89EPAM Systems72Accenture71Virtusa67Siemens65razorpay65Capgemini62Nutanix60Walmart Labs53American Express53Samsung53Deloitte50Zoho42IBM35Oracle27
Problem
Rotate the array nums to the right by k steps, in place: each element moves k positions right, wrapping around the end.
Example: nums = [1,2,3,4,5,6,7], k = 3 → [5,6,7,1,2,3,4]
Constraints: n ≤ 10⁵; k can be larger than n. Follow-up: O(1) extra space.
Rotating right by k = reverse all, then reverse the first k, then reverse the rest.
[1 2 3 4 5 6 7], k=3
reverse all [7 6 5 4 3 2 1]
reverse [0,3) [5 6 7 | 4 3 2 1]
reverse [3,7) [5 6 7 | 1 2 3 4]
Complexity: O(n) time, O(1) space.
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
def rev(i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i, j = i + 1, j - 1
n = len(nums)
k %= n
rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
a = [1, 2, 3, 4, 5, 6, 7]; Solution().rotate(a, 3)
assert a == [5, 6, 7, 1, 2, 3, 4]
b = [-1, -100, 3, 99]; Solution().rotate(b, 2)
assert b == [3, 99, -1, -100]
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k %= n;
rev(nums, 0, n - 1);
rev(nums, 0, k - 1);
rev(nums, k, n - 1);
}
private void rev(int[] a, int i, int j) {
while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}
}
func rotate(nums []int, k int) {
rev := func(i, j int) {
for ; i < j; i, j = i+1, j-1 {
nums[i], nums[j] = nums[j], nums[i]
}
}
n := len(nums)
k %= n
rev(0, n-1)
rev(0, k-1)
rev(k, n-1)
}