Given an array, rotate the array to the right by k steps, where k is non-negative.
k and size of the array (n):
n (the length of the array) and k?k always less than or equal to n?Normalize k: Since rotating by n is equivalent to not rotating at all, we can use k % n to handle cases where k is greater than n.
k elements.n - k elements.nums = [1,2,3,4,5,6,7], k = 3[7,6,5,4,3,2,1][5,6,7,4,3,2,1][5,6,7,1,2,3,4][5,6,7,1,2,3,4]public class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k = k % n; // Normalize k
// Reverse entire array
reverse(nums, 0, n - 1);
// Reverse first k elements
reverse(nums, 0, k - 1);
// Reverse remaining n-k elements
reverse(nums, k, n - 1);
}
private void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}
}
This solution efficiently rotates the array using the reversal method while maintaining an in-place operation and linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?