Open In App

Left Rotation of a String

Last Updated : 11 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given a string s and an integer d, the task is to left rotate the string by d positions.

Examples:

Input: s = “GeeksforGeeks”, d = 2
Output: “eksforGeeksGe”
Explanation: After the first rotation, string s becomes “eeksforGeeksG” and after the second rotation, it becomes “eksforGeeksGe”.

Input: s = “qwertyu”, d = 2
Output: “ertyuqw”
Explanation: After the first rotation, string s becomes “wertyuq” and after the second rotation, it becomes “ertyuqw”.

[Naive Approach] Left Rotate one by one

The idea is to store the first character in a variable and shift all the remaining characters to the left by one position, then place the first character at the end of string. This process is repeated d times.

C++
// C++ Program to left rotate the string by d 
// positions by rotating one element at a time

#include <iostream>
#include <string>
using namespace std;
 
void rotateString(string &s, int d) {
    int n = s.size();

    // Repeat the rotation d times
    for (int i = 0; i < d; i++) {

        // Left rotate the string by one position
        int first = s[0];
        for (int j = 0; j < n - 1; j++) 
            s[j] = s[j + 1];
      
          // Place the first character at the end
        s[n - 1] = first;
    }
}

int main() {
    string s = "GeeksforGeeks";
    int d = 2;
    rotateString(s, d);
    cout << s << endl;
    return 0;
}
C Java Python C# JavaScript

Output
eksforGeeksGe

Time Complexity: O(n*d), the outer loop runs d times, and inner loop runs n times.
Auxiliary Space: O(1) if the string is mutable, like in C++. For immutable strings like in Java, C#, Python and Javascript an extra character array of size n is used, so the space complexity will be O(n).

[Better Approach] Using Temporary Char Array

The idea is to use a temporary character array of size n (size of original string). If we left rotate the string by d positions, the last n – d elements will be at the front and the first d elements will be at the end.

  • Copy the last (n – d) elements of original string into the first n – d positions of temporary array.
  • Then, copy the first d elements of the original string to the end of temporary array.
  • Finally, convert the temporary char array to the string.
C++
// C++ program to left rotate a string by d
// position using a temporary array

#include <iostream>
#include <string>
using namespace std;

string rotateString(string &s, int d) {
    int n = s.length();

    // Handle cases where d > n
    d = d % n;
    char temp[n];

    // Copy the last (n - d) characters
    // to the start of temp Array
    for (int i = 0; i < n - d; i++)
        temp[i] = s[d + i];

    // Copy the first d characters to the end
    // of temp Array
    for (int i = 0; i < d; i++)
        temp[n - d + i] = s[i];

    // Convert temp array to the string
    return string(temp, n);
}

int main() {
    string s = "GeeksforGeeks";
    int d = 2;
    string rotatedString = rotateString(s, d);
    cout << rotatedString << endl;
    return 0;
}
Java Python C# JavaScript

Output
eksforGeeksGe

Time Complexity: O(n), as we are visiting each element only twice.
Auxiliary Space: O(n), as we are using an additional character array.

[Expected Approach – 1] Using Juggling Algorithm

The idea behind the juggling algorithm is that we can rotate all the elements in cycle. Each cycle is independent and represents a group of elements that will shift among themselves during the rotation. If the starting index of a cycle is i, then next elements of the cycle will be present at indices (i + d) % n, (i + 2d) % n, (i + 3d) % n … and so on till we reach back to index i. The total number of cycles will be GCD of n and d. And, we perform a single left rotation within each cycle.

To know more about the Juggling algorithm, refer this article – Juggling Algorithm for Array Rotation.

C++
// C++ Program to left rotate the string by d positions
// using Juggling Algorithm

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void rotateString(string &s, int d) {
    int n = s.size();

    // Handle the case where d > size of array
    d %= n;

    // Calculate the number of cycles in the rotation
    int cycles = __gcd(n, d);

    // Perform a left rotation within each cycle
    for (int i = 0; i < cycles; i++) {

        // Start element of current cycle
        char startChar = s[i];

        // Start index of current cycle
        int currIdx = i, nextIdx;

        // Rotate elements till we reach the start of cycle
        while (true) {
            nextIdx = (currIdx + d) % n;

            if (nextIdx == i)
                break;

            // Update the next index with the current element
            s[currIdx] = s[nextIdx];
            currIdx = nextIdx;
        }

        // Copy the start element of current cycle 
        // at the last index of the cycle
        s[currIdx] = startChar;
    }
}

int main() {
    string s = "GeeksforGeeks";
    int d = 2;
    rotateString(s, d);
    cout << s << endl;
    return 0;
}
C Java Python C# JavaScript

Output
eksforGeeksGe

Time Complexity: O(n)
Auxiliary Space: O(1) if the string is mutable, like in C++. For immutable strings like in Java, C#, Python and Javascript an extra character array of size n is used, so the space complexity will be O(n).

[Expected Approach – 2] Using Reversal Algorithm

The idea is based on the observation that if we left rotate the string by d positions, the last (n – d) elements will be at the front and the first d elements will be at the end.

  • Reverse the substring containing the first d elements of the string.
  • Reverse the substring containing the last (n – d) elements of the string.
  • Finally, reverse all the elements of the string.
C++
// C++ program to left rotate a string by d position
// using Reversal Algorithm

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void rotateString(string &s, int d) {
    int n = s.size();

    // Handle the case where d > size of array
    d %= n;

    // Reverse the first d elements
    reverse(s.begin(), s.begin() + d);

    // Reverse the remaining n-d elements
    reverse(s.begin() + d, s.end());

    // Reverse the entire  string
    reverse(s.begin(), s.end());
}

int main() {
    string s = "GeeksforGeeks";
    int d = 2;
    rotateString(s, d);
    cout << s << endl;
    return 0;
}
Java Python C# JavaScript

Output
eksforGeeksGe

Time Complexity: O(n), where n is the size of the given string.
Auxiliary Space: O(1) if the string is mutable, like in C++. For immutable strings like in Java, C#, python and Javascript, an extra character array of size n is used, so the space complexity will be O(n).



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg