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.
- Arrays: Left Rotation
- Discussions
Arrays: Left Rotation
Arrays: Left Rotation
Sort by
recency
|
4973 Discussions
|
Please Login in order to post a comment
C# this is with basic knowledge
public static List rotLeft(List a, int d) {
}
Solution for c#.
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; }
Java
public static List rotLeft(List a, int d) { while(d>0) { Integer removed = a.remove(0); a.add(removed); d--; } return a; } }