Skip to content

Commit a5f57fb

Browse files
authored
refactor: ArrayLeftRotationTest (#5389)
1 parent 3187b1f commit a5f57fb

File tree

2 files changed

+33
-16
lines changed

2 files changed

+33
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,44 @@
11
package com.thealgorithms.others;
22

3-
/*
4-
* A left rotation operation on an array
5-
* shifts each of the array's elements
6-
* given integer n unit to the left.
3+
/**
4+
* Provides a method to perform a left rotation on an array.
5+
* A left rotation operation shifts each element of the array
6+
* by a specified number of positions to the left.
77
*
88
* @author sangin-lee
99
*/
10-
1110
public final class ArrayLeftRotation {
1211
private ArrayLeftRotation() {
1312
}
1413

15-
/*
16-
* Returns the result of left rotation of given array arr and integer n
17-
*
18-
* @param arr : int[] given array
19-
*
20-
* @param n : int given integer
14+
/**
15+
* Performs a left rotation on the given array by the specified number of positions.
2116
*
22-
* @return : int[] result of left rotation
17+
* @param arr the array to be rotated
18+
* @param n the number of positions to rotate the array to the left
19+
* @return a new array containing the elements of the input array rotated to the left
2320
*/
2421
public static int[] rotateLeft(int[] arr, int n) {
2522
int size = arr.length;
26-
int[] dst = new int[size];
23+
24+
// Handle cases where array is empty or rotation count is zero
25+
if (size == 0 || n <= 0) {
26+
return arr.clone();
27+
}
28+
29+
// Normalize the number of rotations
2730
n = n % size;
31+
if (n == 0) {
32+
return arr.clone();
33+
}
34+
35+
int[] rotated = new int[size];
36+
37+
// Perform rotation
2838
for (int i = 0; i < size; i++) {
29-
dst[i] = arr[n];
30-
n = (n + 1) % size;
39+
rotated[i] = arr[(i + n) % size];
3140
}
32-
return dst;
41+
42+
return rotated;
3343
}
3444
}

src/test/java/com/thealgorithms/others/ArrayLeftRotationTest.java

+7
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,11 @@ void testForHigherSizeStep() {
4444
int[] result = ArrayLeftRotation.rotateLeft(arr, n);
4545
assertArrayEquals(expected, result);
4646
}
47+
48+
@Test
49+
void testForEmptyArray() {
50+
int[] arr = {};
51+
int[] result = ArrayLeftRotation.rotateLeft(arr, 3);
52+
assertArrayEquals(arr, result);
53+
}
4754
}

0 commit comments

Comments
 (0)