You are viewing a single comment's thread. Return to all comments →
We can optimize the space complexity in the following way:
O(n)
O(1)
Approach:
LeftRotation(ar, n, d) { reverse(0, n-1, ar); reverse(0, n-d-1, ar); reverse(n-d, n-1, ar); }
Code:
public static void main(String[] args) { int[] ar = {1, 2, 3, 4, 5}; rotate(ar, ar.length, 4); Arrays.stream(ar).forEach(i -> System.out.print(i + " ")); } public static void rotate(int[] ar, int n, int d) { reverse(ar, 0, n - 1); reverse(ar, 0, n - d - 1); reverse(ar, n - d, n - 1); } private static void reverse(int[] ar, int l, int r) { while (l < r) { int temp = ar[r]; ar[r] = ar[l]; ar[l] = temp; l++; r--; } }
Left Rotation
You are viewing a single comment's thread. Return to all comments →
We can optimize the space complexity in the following way:
O(n)
O(1)
Approach:
Code: