Generate all rotations of a given string
Last Updated :
17 Jul, 2024
Given a string S. The task is to print all the possible rotated strings of the given string.
Examples:
Input : S = "geeks"
Output : geeks
eeksg
eksge
ksgee
sgeek
Input : S = "abc"
Output : abc
bca
cab
Method 1 (Simple): The idea is to run a loop from i = 0 to n - 1 ( n = length of string) i.e for each point of rotation, copy the second part of the string in the temporary string and then copy the first part of the original string to the temporary string.
Below is implementation of the above approach:
C++
// A simple C++ program to generate all rotations
// of a given string
#include<bits/stdc++.h>
using namespace std;
// Print all the rotated string.
void printRotatedString(char str[])
{
int len = strlen(str);
// Generate all rotations one by one and print
char temp[len];
for (int i = 0; i < len; i++)
{
int j = i; // Current index in str
int k = 0; // Current index in temp
// Copying the second part from the point
// of rotation.
while (str[j] != '\0')
{
temp[k] = str[j];
k++;
j++;
}
// Copying the first part from the point
// of rotation.
j = 0;
while (j < i)
{
temp[k] = str[j];
j++;
k++;
}
printf("%s\n", temp);
}
}
// Driven Program
int main()
{
char str[] = "geeks";
printRotatedString(str);
return 0;
}
Java
// A simple Java program to generate all rotations
// of a given string
class Test
{
// Print all the rotated string.
static void printRotatedString(String str)
{
int len = str.length();
// Generate all rotations one by one and print
StringBuffer sb;
for (int i = 0; i < len; i++)
{
sb = new StringBuffer();
int j = i; // Current index in str
int k = 0; // Current index in temp
// Copying the second part from the point
// of rotation.
for (int k2 = j; k2 < str.length(); k2++) {
sb.insert(k, str.charAt(j));
k++;
j++;
}
// Copying the first part from the point
// of rotation.
j = 0;
while (j < i)
{
sb.insert(k, str.charAt(j));
j++;
k++;
}
System.out.println(sb);
}
}
// Driver method
public static void main(String[] args)
{
String str = new String("geeks");
printRotatedString(str);
}
}
Python
# A simple Python3 program to generate
# all rotations of a given string
# Print all the rotated strings.
def printRotatedString(str):
lenn = len(str)
# Generate all rotations
# one by one and print
temp = [0] * (lenn)
for i in range(lenn):
j = i # Current index in str
k = 0 # Current index in temp
# Copying the second part from
# the point of rotation.
while (j < len(str)):
temp[k] = str[j]
k += 1
j += 1
# Copying the first part from
# the point of rotation.
j = 0
while (j < i) :
temp[k] = str[j]
j += 1
k += 1
print(*temp, sep = "")
# Driver Code
if __name__ == '__main__':
str = "geeks"
printRotatedString(str)
# This code is contributed
# by SHUBHAMSINGH10
C#
// A simple C# program to generate
// all rotations of a given string
using System;
using System.Text;
class GFG
{
// Print all the rotated string.
public static void printRotatedString(string str)
{
int len = str.Length;
// Generate all rotations one
// by one and print
StringBuilder sb;
for (int i = 0; i < len; i++)
{
sb = new StringBuilder();
int j = i; // Current index in str
int k = 0; // Current index in temp
// Copying the second part from
// the point of rotation.
for (int k2 = j; k2 < str.Length; k2++)
{
sb.Insert(k, str[j]);
k++;
j++;
}
// Copying the first part from
// the point of rotation.
j = 0;
while (j < i)
{
sb.Insert(k, str[j]);
j++;
k++;
}
Console.WriteLine(sb);
}
}
// Driver Code
public static void Main(string[] args)
{
string str = "geeks";
printRotatedString(str);
}
}
// This code is contributed
// by Shrikant13
JavaScript
<script>
// A simple javascript program to generate
// all rotations of a given string
// Print all the rotated string.
function printRotatedString(str)
{
var len = str.length;
// Generate all rotations one
// by one and print
var sb;
for(i = 0; i < len; i++)
{
sb = [];
// Current index in str
var j = i;
// Current index in temp
var k = 0;
// Copying the second part from the point
// of rotation.
for(k2 = j; k2 < str.length; k2++)
{
sb.push(str.charAt(j));
k++;
j++;
}
// Copying the first part from the point
// of rotation.
j = 0;
while (j < i)
{
sb.push(str.charAt(j));
j++;
k++;
}
document.write(sb.join("") + "<br>");
}
}
// Driver code
var str = "geeks";
printRotatedString(str);
// This code is contributed by Amit Katiyar
</script>
PHP
<?php
// A simple PHP program to generate
// all rotations of a given string
// Print all the rotated string.
function printRotatedString($str)
{
$len = strlen($str);
// Generate all rotations one
// by one and print
$temp = " ";
for ($i = 0; $i < $len; $i++)
{
$j = $i; // Current index in str
$k = 0; // Current index in temp
// Copying the second part from
// the point of rotation.
while ($j < $len)
{
$temp[$k] = $str[$j];
$k++;
$j++;
}
// Copying the first part from
// the point of rotation.
$j = 0;
while ($j < $i)
{
$temp[$k] = $str[$j];
$j++;
$k++;
}
echo $temp . "\n";
}
}
// Driver Code
$str = "geeks";
printRotatedString($str);
// This code is contributed
// by Akanksha Rai
?>
Outputgeeks
eeksg
eksge
ksgee
sgeek
Time complexity: O(n2) where n is length of string
Auxiliary Space: O(n)
Method 2 (Tricky and Efficient): The idea is based on the efficient method to check if strings are rotations of each other or not. We concatenate str with itself, i.e., we do str.str where . is concatenation operator. Now we traverse the concatenated string from 0 to n - 1 and print all substrings of size n.
Below is the implementation of above approach:
C++
// An efficient C++ program to print all
// rotations of a string. Space complexity O(1).
#include<bits/stdc++.h>
using namespace std;
// Print all the rotated string.
void printRotatedString(char str[])
{
int n = strlen(str);
int i,j,k;
for (i=0; i<n; i++)
{
k=i;
for (j=0; j<n; j++)
{
cout << str[ (k++) % n ];
}
cout << endl;
}
}
// Driven Program
int main()
{
char str[] = "geeks";
printRotatedString(str);
return 0;
}
Java
// A simple Java program to generate all rotations
// of a given string
class Test
{
// Print all the rotated string.
static void printRotatedString(String str)
{
int n = str.length();
StringBuffer sb = new StringBuffer(str);
// Concatenate str with itself
sb.append(str);
// Print all substrings of size n.
// Note that size of sb is 2n
for (int i = 0; i < n; i++)
{
for (int j=0; j != n; j++)
System.out.print(sb.charAt(i + j));
System.out.println();
}
}
// Driver method
public static void main(String[] args)
{
String str = new String("geeks");
printRotatedString(str);
}
}
Python
# An efficient Python3 program to print
# all rotations of a string.
# Print all the rotated string.
def printRotatedString(string) :
n = len(string)
# Concatenate str with itself
temp = string + string
# Print all substrings of size n.
# Note that size of temp is 2n
for i in range(n) :
for j in range(n) :
print(temp[i + j], end = "")
print()
# Driver Code
if __name__ == "__main__" :
string = "geeks"
printRotatedString(string)
# This code is contributed by Ryuga
C#
// A simple C# program to generate all rotations
// of a given string
using System;
using System.Text;
class Test
{
// Print all the rotated string.
static void printRotatedString(String str)
{
int n = str.Length;
StringBuilder sb = new StringBuilder(str);
// Concatenate str with itself
sb.Append(str);
// Print all substrings of size n.
// Note that size of sb is 2n
for (int i = 0; i < n; i++)
{
for (int j=0; j != n; j++)
Console.Write(sb[i + j]);
Console.WriteLine();
}
}
// Driver method
public static void Main(String[] args)
{
String str = "geeks";
printRotatedString(str);
}
}
JavaScript
<script>
// A simple javascript program to generate all rotations
// of a given string
// Print all the rotated string.
function printRotatedString(str)
{
var n = str.length;
var sb = str;
// Concatenate str with itself
sb += (str);
// Print all substrings of size n.
// Note that size of sb is 2n
for (var i = 0; i < n; i++)
{
for (var j = 0; j != n; j++)
document.write(sb.charAt(i + j));
document.write('<br>');
}
}
// Driver method
var str = "geeks";
printRotatedString(str);
// This code is contributed by 29AjayKumar
</script>
PHP
<?php
// An efficient PHP program to print all
// rotations of a string.
// Print all the rotated string.
function printRotatedString($str)
{
$n = strlen($str);
// Concatenate str with itself
$temp=$str.$str;
// Print all substrings of size n.
// Note that size of temp is 2n
for ($i = 0; $i < $n; $i++)
{
for ($j = 0; $j != $n; $j++)
print($temp[$i + $j]);
print("\n");
}
}
// Driver code
$str = "geeks";
printRotatedString($str);
// This code is contributed by mits
?>
Outputgeeks
eeksg
eksge
ksgee
sgeek
Time complexity: O(n2) where n is length of string
Auxiliary Space : O(n)
Similar Reads
Left Rotation of a String Given a string s and an integer d, the task is to left rotate the string by d positions.Examples:Input: s = "GeeksforGeeks", d = 2Output: "eksforGeeksGe" Explanation: After the first rotation, string s becomes "eeksforGeeksG" and after the second rotation, it becomes "eksforGeeksGe".Input: s = "qwer
15+ min read
Check if a given string is a rotation of a palindrome Given a string, check if it is a rotation of a palindrome. For example your function should return true for "aab" as it is a rotation of "aba". Examples: Input: str = "aaaad" Output: 1 // "aaaad" is a rotation of a palindrome "aadaa" Input: str = "abcd" Output: 0 // "abcd" is not a rotation of any p
15+ min read
Javascript Program to Generate all rotations of a number Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
2 min read
Permutations of a given string using STL Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order.Note: A permutation is the rearrangement of all the elements of a string.Examples:Input: s = "ABC"Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB"Input: s = "XY"Output: "XY", "YX"Input
4 min read
Check if Strings Are Rotations of Each Other Given two string s1 and s2 of same length, the task is to check whether s2 is a rotation of s1.Examples: Input: s1 = "abcd", s2 = "cdab"Output: trueExplanation: After 2 right rotations, s1 will become equal to s2.Input: s1 = "aab", s2 = "aba"Output: trueExplanation: After 1 left rotation, s1 will be
15+ min read