Check if strings are rotations of each other or not | Set 2
Last Updated :
19 Aug, 2022
Given two strings s1 and s2, check whether s2 is a rotation of s1.
Examples:
Input : ABACD, CDABA
Output : True
Input : GEEKS, EKSGE
Output : True
We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest proper prefix which is also suffix) construction, which will help in finding the longest match of the prefix of string b and suffix of string a. By which we will know the rotating point, from this point match the characters. If all the characters are matched, then it is a rotation, else not.
Below is the basic implementation of the above approach.
C++
// C++ program to check if
// two strings are rotations
// of each other
#include<bits/stdc++.h>
using namespace std;
bool isRotation(string a,
string b)
{
int n = a.length();
int m = b.length();
if (n != m)
return false;
// create lps[] that
// will hold the longest
// prefix suffix values
// for pattern
int lps[n];
// length of the previous
// longest prefix suffix
int len = 0;
int i = 1;
// lps[0] is always 0
lps[0] = 0;
// the loop calculates
// lps[i] for i = 1 to n-1
while (i < n)
{
if (a[i] == b[len])
{
lps[i] = ++len;
++i;
}
else
{
if (len == 0)
{
lps[i] = 0;
++i;
}
else
{
len = lps[len - 1];
}
}
}
i = 0;
// Match from that rotating
// point
for (int k = lps[n - 1];
k < m; ++k)
{
if (b[k] != a[i++])
return false;
}
return true;
}
// Driver code
int main()
{
string s1 = "ABACD";
string s2 = "CDABA";
cout << (isRotation(s1, s2) ?
"1" : "0");
}
// This code is contributed by Chitranayal
Java
// Java program to check if two strings are rotations
// of each other.
import java.util.*;
import java.lang.*;
import java.io.*;
class stringMatching {
public static boolean isRotation(String a, String b)
{
int n = a.length();
int m = b.length();
if (n != m)
return false;
// create lps[] that will hold the longest
// prefix suffix values for pattern
int lps[] = new int[n];
// length of the previous longest prefix suffix
int len = 0;
int i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to n-1
while (i < n) {
if (a.charAt(i) == b.charAt(len)) {
lps[i] = ++len;
++i;
}
else {
if (len == 0) {
lps[i] = 0;
++i;
}
else {
len = lps[len - 1];
}
}
}
i = 0;
// match from that rotating point
for (int k = lps[n - 1]; k < m; ++k) {
if (b.charAt(k) != a.charAt(i++))
return false;
}
return true;
}
// Driver code
public static void main(String[] args)
{
String s1 = "ABACD";
String s2 = "CDABA";
System.out.println(isRotation(s1, s2) ? "1" : "0");
}
}
Python3
# Python program to check if
# two strings are rotations
# of each other
def isRotation(a: str, b: str) -> bool:
n = len(a)
m = len(b)
if (n != m):
return False
# create lps[] that
# will hold the longest
# prefix suffix values
# for pattern
lps = [0 for _ in range(n)]
# length of the previous
# longest prefix suffix
length = 0
i = 1
# lps[0] is always 0
lps[0] = 0
# the loop calculates
# lps[i] for i = 1 to n-1
while (i < n):
if (a[i] == b[length]):
length += 1
lps[i] = length
i += 1
else:
if (length == 0):
lps[i] = 0
i += 1
else:
length = lps[length - 1]
i = 0
# Match from that rotating
# point
for k in range(lps[n - 1], m):
if (b[k] != a[i]):
return False
i += 1
return True
# Driver code
if __name__ == "__main__":
s1 = "ABACD"
s2 = "CDABA"
print("1" if isRotation(s1, s2) else "0")
# This code is contributed by sanjeev2552
C#
// C# program to check if
// two strings are rotations
// of each other.
using System;
class GFG
{
public static bool isRotation(string a,
string b)
{
int n = a.Length;
int m = b.Length;
if (n != m)
return false;
// create lps[] that will
// hold the longest prefix
// suffix values for pattern
int []lps = new int[n];
// length of the previous
// longest prefix suffix
int len = 0;
int i = 1;
// lps[0] is always 0
lps[0] = 0;
// the loop calculates
// lps[i] for i = 1 to n-1
while (i < n)
{
if (a[i] == b[len])
{
lps[i] = ++len;
++i;
}
else
{
if (len == 0)
{
lps[i] = 0;
++i;
}
else
{
len = lps[len - 1];
}
}
}
i = 0;
// match from that
// rotating point
for (int k = lps[n - 1]; k < m; ++k)
{
if (b[k] != a[i++])
return false;
}
return true;
}
// Driver code
public static void Main()
{
string s1 = "ABACD";
string s2 = "CDABA";
Console.WriteLine(isRotation(s1, s2) ?
"1" : "0");
}
}
// This code is contributed
// by anuj_67.
JavaScript
<script>
// javascript program to check if two strings are rotations
// of each other.
function isRotation(a, b)
{
var n = a.length;
var m = b.length;
if (n != m)
return false;
// create lps that will hold the longest
// prefix suffix values for pattern
var lps = Array.from({length: n}, (_, i) => 0);
// length of the previous longest prefix suffix
var len = 0;
var i = 1;
lps[0] = 0; // lps[0] is always 0
// the loop calculates lps[i] for i = 1 to n-1
while (i < n) {
if (a.charAt(i) == b.charAt(len)) {
lps[i] = ++len;
++i;
}
else {
if (len == 0) {
lps[i] = 0;
++i;
}
else {
len = lps[len - 1];
}
}
}
i = 0;
// match from that rotating point
for (k = lps[n - 1]; k < m; ++k) {
if (b.charAt(k) != a.charAt(i++))
return false;
}
return true;
}
// Driver code
var s1 = "ABACD";
var s2 = "CDABA";
document.write(isRotation(s1, s2) ? "1" : "0");
// This code is contributed by shikhasingrajput.
</script>
Complexity Analysis:
- Time Complexity: O(n)
- Auxiliary Space: O(n)
Similar Reads
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
POTD Solutions | 14 Nov'23 | Check if strings are rotations of each other or not View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of String but will also help you build up problem-solving
3 min read
Javascript Program to Check if strings are rotations of each other or not | Set 2 Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples: Input : ABACD, CDABAOutput : TrueInput : GEEKS, EKSGEOutput : TrueWe have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (longest
2 min read
Check if two strings are permutation of each other Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that
13 min read
Check if two numbers are bit rotations of each other or not Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input :
6 min read