Rotate - cywongg/2025 GitHub Wiki
public static int[] rotate(int[] A, int k) {
2 int rightShift = k % A.length;
3 if (rightShift < 0) {
4 rightShift += A.length;
5 }
6
7 int[] newArr = new int[A.length];
8 for (int i = 0; i < A.length; i++) {
9 int newIndex = (i + rightShift) % A.length;
10 newArr[newIndex] = A[i];
11 }
12 return newArr;
13 }
14
Note that int rightShift = (k % A.length) + A.length could work in one line (as opposed to making an
additional check for negative rightShift) because the modulo would take care of overflows for additions to
positive k values.
Explanation:
First we calculate the actual number of positions to shift by using the modulus operator mod with the length
of A. This ensures that rightShift is always a non-negative integer between 0 and A.length-1.
If k is negative, then rightShift will be negative after the modulus operation mod A.length. For example,
if A has length 5 and k is -2, then rightShift will be -2 mod 5 = -2. Then adding A.length to rightShift
makes it positive and shifts the array to the left by 2 positions, which is the opposite direction of the original
shift. For example, rightShift += 5 becomes rightShift = 3, which means the array is shifted to the left by
2 positions.
Then we move on to the second half where we create a new array newArr with the same length as A to store
the shifted elements. It we iterate over the original array A and calculate the new index for each element by
adding rightShift to the current index and taking the result modulo A.length.
This calculation ensures that the shifted element ”wraps around” to the beginning of the array if it goes
beyond the last index. Then we assign the original element to the corresponding index in the new array
Alternate:
1 public static int[] rotate(int[] A, int k) {
2 int rightShift = 330; // don't need this
3 if (k < 0) {
4 return rotate(A, k + A.length);
5 }
6
7 int[] newArr = new int[A.length];
8 for (int i = 0; i < A.length; i++) {
9 int newIndex = (i + k) % A.length;
10 newArr[newIndex] = A[i];
11 }
12 return newArr;
13 }
14
Explanation: For positive values of k, this solution is essentially the same as the previous one. For negative
values of k, we repeatedly add A.length until it is positive, which is essentially what modulo does.