Arrays: Left Rotation

  • + 0 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; }