We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Here is the optimal approach by using recursion and reversing the array.
//swap array elements
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
void reverse(vector &arr, int i, int j) {
if (i >= j) return; // Base condition to stop recursion
swap(arr[i], arr[j]);
reverse(arr, i + 1, j - 1);
}
vector rotLeft(vector a, int d) {
int n = a.size();
d = d % n; // Handle cases where d >= n
reverse(a, 0, d - 1); // Reverse the first part
reverse(a, d, n - 1); // Reverse the second part
reverse(a, 0, n - 1); // Reverse the whole array
return a;
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Arrays: Left Rotation
You are viewing a single comment's thread. Return to all comments →
Here is the optimal approach by using recursion and reversing the array.
//swap array elements void swap(int &a, int &b) { int temp = a; a = b; b = temp; }
void reverse(vector &arr, int i, int j) { if (i >= j) return; // Base condition to stop recursion swap(arr[i], arr[j]); reverse(arr, i + 1, j - 1); }
vector rotLeft(vector a, int d) { int n = a.size(); d = d % n; // Handle cases where d >= n reverse(a, 0, d - 1); // Reverse the first part reverse(a, d, n - 1); // Reverse the second part reverse(a, 0, n - 1); // Reverse the whole array return a; }