Rotate an array by K positions in java

public static int[] rotateArray(int[] arr, int k) {
    int n = arr.length;
    // If k is greater than n, take the modulus to get the actual rotation amount
    k = k % n;
    // Reverse the last k elements
    reverseArray(arr, n - k, n - 1);
    // Reverse the first n-k elements
    reverseArray(arr, 0, n - k - 1);
    // Reverse the entire array
    reverseArray(arr, 0, n - 1);
    return arr;
}

private static void reverseArray(int[] arr, int start, int end) {
    while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

This implementation is similar to the Python implementation, but uses an auxiliary function to reverse a subarray of the array. The rotateArray function first calculates the actual rotation amount by taking the modulus of k with the length of the array. Then it reverses the last k elements, followed by the first n-k elements. Finally, it reverses the entire array to get the final rotated array.

For example, let's rotate the array [1, 2, 3, 4, 5] by 2 positions to the right:

int[] arr = {1, 2, 3, 4, 5};
int k = 2;
arr = rotateArray(arr, k);
System.out.println(Arrays.toString(arr));

The time complexity of rotating an array by K positions using the implementation provided in the previous answers is O(n), where n is the length of the array.

The implementation performs three reverse operations on the array, each of which takes O(n/2) time, since they reverse half the array elements. The time complexity of the reverseArray function is therefore O(n/2), which is equivalent to O(n). The rotateArray function calls reverseArray three times, so the total time complexity is O(3n/2), which simplifies to O(n).

Note that the time complexity of the implementation may vary depending on the specific operation being performed on the array, and there may be other algorithms with different time complexities to solve the same problem. However, the implementation provided above is a straightforward and efficient solution for the task of rotating an array by K positions.