Skip to content

Commit 54c214c

Browse files
committed
Add array rotation utility using reversal algorithm
1 parent 2616e09 commit 54c214c

1 file changed

Lines changed: 85 additions & 0 deletions

File tree

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.thealgorithms.others;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Array Rotation Utility
7+
*
8+
* Supports:
9+
* 1. Left Rotation
10+
* 2. Right Rotation
11+
*
12+
* Approach:
13+
* Reversal Algorithm
14+
*
15+
* Time Complexity: O(n)
16+
* Space Complexity: O(1)
17+
*/
18+
19+
public class ArrayRotation {
20+
21+
/**
22+
* Rotates the array to the right by k positions.
23+
*
24+
* @param nums the input array
25+
* @param k number of rotations
26+
*/
27+
28+
public static void rotateRight(int[] nums, int k) {
29+
30+
int n = nums.length;
31+
32+
if (n == 0) {
33+
return;
34+
}
35+
36+
k = k % n;
37+
38+
reverse(nums, 0, n - 1);
39+
reverse(nums, 0, k - 1);
40+
reverse(nums, k, n - 1);
41+
42+
}
43+
44+
/**
45+
* Rotates the array to the left by k positions.
46+
*
47+
* @param nums the input array
48+
* @param k number of rotations
49+
*/
50+
51+
public static void rotateLeft(int[] nums, int k) {
52+
53+
int n = nums.length;
54+
55+
if (n == 0) {
56+
return;
57+
}
58+
59+
k = k % n;
60+
61+
reverse(nums, 0, k - 1);
62+
reverse(nums, k, n - 1);
63+
reverse(nums, 0, n - 1);
64+
}
65+
66+
/**
67+
* Reverses elements between start and end indices.
68+
*
69+
* @param nums the input array
70+
* @param start starting index
71+
* @param end ending index
72+
*/
73+
private static void reverse(int[] nums, int start, int end) {
74+
75+
while (start < end) {
76+
77+
int temp = nums[start];
78+
nums[start] = nums[end];
79+
nums[end] = temp;
80+
81+
start++;
82+
end--;
83+
}
84+
}
85+
}

0 commit comments

Comments
 (0)