|
1 | 1 | package com.thealgorithms.others;
|
2 | 2 |
|
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. |
7 | 7 | *
|
8 | 8 | * @author sangin-lee
|
9 | 9 | */
|
10 |
| - |
11 | 10 | public final class ArrayLeftRotation {
|
12 | 11 | private ArrayLeftRotation() {
|
13 | 12 | }
|
14 | 13 |
|
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. |
21 | 16 | *
|
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 |
23 | 20 | */
|
24 | 21 | public static int[] rotateLeft(int[] arr, int n) {
|
25 | 22 | 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 |
27 | 30 | n = n % size;
|
| 31 | + if (n == 0) { |
| 32 | + return arr.clone(); |
| 33 | + } |
| 34 | + |
| 35 | + int[] rotated = new int[size]; |
| 36 | + |
| 37 | + // Perform rotation |
28 | 38 | for (int i = 0; i < size; i++) {
|
29 |
| - dst[i] = arr[n]; |
30 |
| - n = (n + 1) % size; |
| 39 | + rotated[i] = arr[(i + n) % size]; |
31 | 40 | }
|
32 |
| - return dst; |
| 41 | + |
| 42 | + return rotated; |
33 | 43 | }
|
34 | 44 | }
|
0 commit comments