Member-only story
Rotate Array
Approach to Solve: Reversal Algorithm
We can solve this problem efficiently using the Reversal Algorithm, which reverses parts of the array instead of creating a new array.
The main idea is to reverse the entire array first and then reverse the two individual sections to get the desired result.
Step 1: Reverse the entire array
Initially:
[1, 2, 3, 4, 5, 6, 7]After reversing the entire array:
[7, 6, 5, 4, 3, 2, 1]Step 2: Reverse the first k elements
Since k = 3, reverse the first three elements:
[5, 6, 7, 4, 3, 2, 1]Step 3: Reverse the remaining elements
Reverse the elements from index k to the last index:
[5, 6, 7, 1, 2, 3, 4]This gives us the final rotated array.
Java Code
class Solution {
public static void reverse(int[] nums, int start, int end) {
while (start < end) {
int temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
start++;
end--;
}
}…




