Left Rotation of a String
Last Updated :
11 Nov, 2024
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
// C Program to left rotate the string by d positions
// by rotating one element at a time
#include <stdio.h>
#include <string.h>
void rotateString(char s[], int d) {
int n = strlen(s);
// Repeat the rotation d times
for (int i = 0; i < d; i++) {
// Left rotate the string by one position
char 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() {
char s[] = "GeeksforGeeks";
int d = 2;
rotateString(s, d);
printf("%s\n", s);
return 0;
}
Java
// Java Program to left rotate the string by d positions
// by rotating one element at a time
import java.util.Arrays;
class GfG {
static String rotateString(String s, int d) {
// Convert the string to a char array
char[] charArray = s.toCharArray();
int n = charArray.length;
// Perform the rotation d times
for (int i = 0; i < d; i++) {
// Store the first character
char first = charArray[0];
// Shift each character one position to
// the left
for (int j = 0; j < n - 1; j++)
charArray[j] = charArray[j + 1];
// Move the first character to the end
charArray[n - 1] = first;
}
return new String(charArray);
}
public static void main(String[] args) {
String s = "GeeksforGeeks";
int d = 2;
String rotatedString = rotateString(s, d);
System.out.println(rotatedString);
}
}
Python
# python Program to left rotate the string by d
# positions by rotating one element at a time
def rotateString(s, d):
# Convert the string to a list of
# characters
s = list(s)
n = len(s)
# Perform the rotation d times
for _ in range(d):
# Store the first character
first = s[0]
# Shift each character one
# position to the left
for i in range(n - 1):
s[i] = s[i + 1]
# Move the first character to the end
s[n - 1] = first
# Convert the list back to a string
return ''.join(s)
s = "GeeksforGeeks"
d = 2
rotatedString = rotateString(s, d)
print(rotatedString)
C#
// C# Program to left rotate the string by d positions
// by rotating one element at a time
using System;
class GfG {
static string rotateString(string s, int d) {
// Convert the string to a character array
char[] charArray = s.ToCharArray();
int n = charArray.Length;
// Perform the rotation d times
for (int i = 0; i < d; i++) {
// Store the first character
char first = charArray[0];
// Shift each character one position to
// the left
for (int j = 0; j < n - 1; j++)
charArray[j] = charArray[j + 1];
// Move the first character to the end
charArray[n - 1] = first;
}
// Convert the character array to a string
return new string(charArray);
}
static void Main() {
string s = "GeeksforGeeks";
int d = 2;
string rotatedString = rotateString(s, d);
Console.WriteLine(rotatedString);
}
}
JavaScript
// Javascript Program to left rotate the string by d positions
// by rotating one element at a time
function rotateString(s, d) {
// Convert the string to an array
let charArray = s.split('');
let n = charArray.length;
// Perform the rotation d times
for (let i = 0; i < d; i++) {
// Store the first character
let first = charArray[0];
// Shift each character one position to the left
for (let j = 0; j < n - 1; j++)
charArray[j] = charArray[j + 1];
// Move the first character to the end
charArray[n - 1] = first;
}
// Convert the array back to a string
return charArray.join('');
}
let s = "GeeksforGeeks";
let d = 2;
let rotatedString = rotateString(s, d);
console.log(rotatedString);
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
// Java program to left rotate a string by d position
// using a temporary array
import java.io.*;
class GfG {
static String rotateString(String s, int d) {
int n = s.length();
// Handle cases where d > n
d = d % n;
char[] temp = new char[n];
// Copy the last (n - d) characters to the
// start of temp array
for (int i = 0; i < n - d; i++)
temp[i] = s.charAt(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.charAt(i);
// Convert the temp array back to the String
return new String(temp);
}
public static void main(String[] args) {
String s = "GeeksforGeeks";
int d = 2;
String rotatedString = rotateString(s, d);
System.out.println(rotatedString);
}
}
Python
# Python program to left rotate a string
# by d position using a temporary array
def rotateString(s, d):
n = len(s)
# Handle cases where d > n
d = d % n
# Create a temporary array of the
# same length as s
temp = [''] * n
# Copy the last (n - d) characters
# to the start of temp array
for i in range(n - d):
temp[i] = s[d + i]
# Copy the first d characters to the
#end of temp array
for i in range(d):
temp[n - d + i] = s[i]
# Convert temp array back to the string
return ''.join(temp)
s = "GeeksforGeeks"
d = 2
rotatedString = rotateString(s, d)
print(rotatedString)
C#
// C# program to left rotate a string by d position
// using temporary array
using System;
class GfG {
static string rotateString(string s, int d) {
int n = s.Length;
// Handle cases where d > n
d = d % n;
char[] temp = new char[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 back to the string
return new string(temp);
}
static void Main() {
string s = "GeeksforGeeks";
int d = 2;
string rotatedString = rotateString(s, d);
Console.WriteLine(rotatedString);
}
}
JavaScript
// Javascript program to left rotate a string
// by d position using temporary array
function rotateString(s, d) {
let n = s.length;
// Handle cases where d > n
d = d % n;
let temp = new Array(n);
// Copy the last (n - d) characters to
// the start of temp array
for (let i = 0; i < n - d; i++)
temp[i] = s[d + i];
// Copy the first d characters
// to the end of temp array
for (let i = 0; i < d; i++)
temp[n - d + i] = s[i];
// Convert the array back to the string
return temp.join("");
}
let s = "GeeksforGeeks";
let d = 2;
let rotatedString = rotateString(s, d);
console.log(rotatedString);
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
// C Program to left rotate the string by d positions
// using Juggling Algorithm
#include <stdio.h>
#include <string.h>
void rotateString(char s[], int d) {
int n = strlen(s);
// 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 the current cycle
char startChar = s[i];
// Start index of the current cycle
int currIdx = i, nextIdx;
// Rotate elements until we return to the
// start of the cycle
while (1) {
nextIdx = (currIdx + d) % n;
if (nextIdx == i)
break;
// Update the current index with the
// element at the next index
s[currIdx] = s[nextIdx];
currIdx = nextIdx;
}
// Place the start element of the current
// cycle at the last index
s[currIdx] = startChar;
}
}
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
char s[] = "GeeksforGeeks";
int d = 2;
rotateString(s, d);
printf("%s\n", s);
return 0;
}
Java
// Java Program to left rotate the string by d positions
// using Juggling Algorithm
import java.io.*;
class GfG {
static String rotateString(String s, int d) {
int n = s.length();
// Handle the case where
// d > size of the string
d %= n;
// Calculate the number of
// cycles (GCD of n and d)
int cycles = gcd(n, d);
// Convert string to character array
char[] arr = s.toCharArray();
// Perform a left rotation within each cycle
for (int i = 0; i < cycles; i++) {
// Start element of current cycle
char temp = arr[i];
int j = i;
while (true) {
int k = (j + d) % n;
if (k == i) {
break;
}
// Move the element to the next index
arr[j] = arr[k];
j = k;
}
// Place the saved element in the
// last position of the cycle
arr[j] = temp;
}
// Convert the rotated character
// array back to a string
return new String(arr);
}
// function to calculate GCD of two numbers
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args) {
String s = "GeeksforGeeks";
int d = 2;
String rotatedString = rotateString(s, d);
System.out.println(rotatedString);
}
}
Python
# python Program to left rotate the string by
# d positions using Juggling Algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
def rotateString(s, d):
n = len(s)
# Handle the case where d > size of
# the string
d %= n
# Calculate the number of cycles (GCD
# of n and d)
cycles = gcd(n, d)
# Convert string to a list of characters
arr = list(s)
# Perfrom a left rotation wihtin each cycle
for i in range(cycles):
# Start element of current cycle
temp = arr[i]
j = i
while True:
k = (j + d) % n
if k == i:
break
# Move the element to the next
# index
arr[j] = arr[k]
j = k
# Place the saved element in the last
# position of the cycle
arr[j] = temp
# Convert the list of characters back to
# a string and return
return ''.join(arr)
s = "GeeksforGeeks"
d = 2
rotatedString = rotateString(s, d)
print(rotatedString)
C#
// C# Program to left rotate the string by d positions
// using Juggling Algorithm
using System;
class GfG {
static int Gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
static string rotateString(string s, int d) {
int n = s.Length;
// Handle the case where d > size of the string
d %= n;
// Calculate the number of cycles (GCD of n and d)
int cycles = Gcd(n, d);
// Convert string to a character array
char[] arr = s.ToCharArray();
// Perform a left rotation within each cycle
for (int i = 0; i < cycles; i++) {
// Start element of the current cycle
char temp = arr[i];
int j = i;
while (true) {
int k = (j + d) % n;
if (k == i)
break;
// Move the element to the next index
arr[j] = arr[k];
j = k;
}
// Place the saved element in the last position
// of the cycle
arr[j] = temp;
}
// Convert the character array back to a string
return new string(arr);
}
static void Main() {
string s = "GeeksforGeeks";
int d = 2;
string rotatedString = rotateString(s, d);
Console.WriteLine(rotatedString);
}
}
JavaScript
// JavaScript Program to left rotate the string by d
// positions using Juggling Algorithm
function gcd(a, b) {
while (b !== 0) {
let temp = b;
b = a % b;
a = temp;
}
return a;
}
function rotateString(s, d) {
let n = s.length;
// Handle the case where d > size of the string
d %= n;
// Calculate the number of cycles (GCD of n and d)
let cycles = gcd(n, d);
// Convert string to a character array
let arr = s.split('');
// Perform a left rotation within each cycle
for (let i = 0; i < cycles; i++) {
// Start element of the current cycle
let temp = arr[i];
let j = i;
while (true) {
let k = (j + d) % n;
if (k === i) {
break;
}
// Move the element to the next index
arr[j] = arr[k];
j = k;
}
// Place the first element in the last position
// of the cycle
arr[j] = temp;
}
// Convert the character array back to a string
return arr.join('');
}
let s = "GeeksforGeeks";
let d = 2;
let rotatedString = rotateString(s, d);
console.log(rotatedString);
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
// Java program to left rotate a string by d position
// using Reversal Algorithm
import java.io.*;
class GfG {
static String rotateString(String s, int d) {
int n = s.length();
// Handle the case where d > size of string
d %= n;
// Convert string to a character array
char[] temp = s.toCharArray();
// Reverse the first d elements
reverse(temp, 0, d - 1);
// Reverse the remaining n-d elements
reverse(temp, d, n - 1);
// Reverse the entire array
reverse(temp, 0, n - 1);
// Convert the array back to a string and return
return new String(temp);
}
static void reverse(char[] temp, int start, int end) {
while (start < end) {
char c = temp[start];
temp[start] = temp[end];
temp[end] = c;
start++;
end--;
}
}
public static void main(String[] args) {
String s = "GeeksforGeeks";
int d = 2;
String rotatedString = rotateString(s, d);
System.out.println(rotatedString);
}
}
Python
# Python program to left rotate a string by d positons
# using Reversal Algorithm
def rotateString(s, d):
n = len(s)
# Handle cases where d > n
d %= n
# Convert the string to a list of characters
temp = list(s)
# Reverse the first d elements
reverse(temp, 0, d - 1)
# Reverse the remaining n - d elements
reverse(temp, d, n - 1)
# Reverse the entire array
reverse(temp, 0, n - 1)
# Convert the list back to a string and return
return ''.join(temp)
def reverse(temp, start, end):
while start < end:
temp[start], temp[end] = temp[end], temp[start]
start += 1
end -= 1
s = "GeeksforGeeks"
d = 2
rotatedString = rotateString(s, d)
print(rotatedString)
C#
// C++ program to left rotate a string by d positions
// using Reversal Algorithm
using System;
class GfG {
static string RotateString(string s, int d) {
int n = s.Length;
// Handle cases where d > n
d %= n;
// Convert the string to a character array
char[] temp = s.ToCharArray();
// Reverse the first d elements
Reverse(temp, 0, d - 1);
// Reverse the remaining n - d elements
Reverse(temp, d, n - 1);
// Reverse the entire array
Reverse(temp, 0, n - 1);
// Convert the character array back to a string
return new string(temp);
}
static void Reverse(char[] temp, int start, int end) {
while (start < end) {
char c = temp[start];
temp[start] = temp[end];
temp[end] = c;
start++;
end--;
}
}
static void Main() {
string s = "GeeksforGeeks";
int d = 2;
string rotatedString = RotateString(s, d);
Console.WriteLine(rotatedString);
}
}
JavaScript
// C++ program to left rotate a string by d position
// using Reversal Algorithm
function rotateString(s, d) {
const n = s.length;
// Handle cases where d > n
d %= n;
// Convert the string to a character array
let temp = s.split("");
// Reverse the first d elements
reverse(temp, 0, d - 1);
// Reverse the remaining n - d elements
reverse(temp, d, n - 1);
// Reverse the entire array
reverse(temp, 0, n - 1);
// Convert the array back to a string
return temp.join("");
}
function reverse(temp, start, end) {
while (start < end) {
// Swap elements
[temp[start], temp[end]]
= [temp[end], temp[start]];
start++;
end--;
}
}
let s = "GeeksforGeeks";
let d = 2;
let rotatedString = rotateString(s, d);
console.log(rotatedString);
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).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem