Check If One String Is A Rotation Of Another String

You are given two Strings 'P' and 'Q' of equal length. Your task is to check whether String 'P' can be converted into String 'Q' by cyclically rotating it to the right any number of times ( Possibly Zero ).

A cyclic rotation to the right on String A consists of taking String A and moving the rightmost character to the leftmost position. For example, if A = "pqrst", then it will be "tpqrs" after one cyclic rotation on A.

For example:

Consider the two strings P = "abfyg" and Q = "gabfy" 
If we cyclically rotate String P to the right once. The resulting string P becomes "gabfy" which is equal to String Q. Therefore it is possible to convert String P to String Q.
Input Format:
The first line of the input contains an integer 'T', denoting the number of test cases.

The first line of each test case contains the String 'P'.

The second line of each test case contains the String 'Q'.
Output Format:
For each test case print 1 if String 'P' can be converted to String 'Q' by cyclically rotating it to the right any number of tines, otherwise print 0.

Print the output of each test case in a new line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= |P| , |Q| <= 10^5
|P| = |Q|

String 'P' and 'Q' both have the same length and contain lowercase English letters only.

Time Limit: 1 sec
Follow Up:
Can you solve this in O(N) time?
AnswerBot
1y

The task is to check if one string can be converted into another string by cyclically rotating it to the right any number of times.

  • Check if the lengths of the two strings are equal. If not, return 0.

  • C...read more

CodingNinjas
author
2y
Brute Force Approach

The idea is to generate all the possible rotations of String P and compare each of them with String Q. To generate the next cyclic rotation of a string P from the current rotation ...read more

CodingNinjas
author
2y
Optimized approach

The idea is to concatenate String P with itself and find out whether String Q is present in the resulting string as a substring. Let res be the string which is formed by the concatenation of String P with itself. This approach works because all the N possible rotations of String P exist in the string res as a substring. 

 

For example consider String A = "pqrr" having length N = 4.

 

The four possible rotations for the above string are "pqrr", "rpqr", "rrpq", "qrrp".

 

The string res which is formed by concatenating the string A with itself is "pqrrpqrr".

 

We can see that all the rotations of String A are a substring of string res

 

To find whether the String Q is present in the string res as a substring we can use string matching algorithms like Knuth-Morris-Pratt algorithm, Boyer-Moore algorithm, Rabin-Karp algorithm

 

In our implementation we will be using Knuth-Morris-Pratt algorithm.

Space Complexity: O(n)Explanation:

O(N), where N denotes the length of the two strings P and Q.

 

In the worst case, the length of the string res is 2*N and the KMP string matching algorithm takes O(N) extra space. Hence, the overall Space complexity is O(N).

Time Complexity: O(n)Explanation:

O(N), where N denotes the length of the two strings P and Q.

 

In the worst case, KMP String matching algorithm takes O(|res|+|Q|) time to check whether ‘Q’ is a substring of “res” or not. Here |res| = 2*N and |Q| = N. Hence, the overall time complexity is O(N).


Java (SE 1.8)
/*

Time Complexity: O(N)
Space Complexity: O(N)

Where N denotes the length of both strings P and Q.
*/

public class Solution
{
// Function that checks whether string a is present in string b as substring using KMP algorithm
public static int isSubstring(String a, String b)
{
// Finding the length of both strings
int m = a.length();
int n = b.length();

// Defining and initializing the pointer variables to preprocess the string a
int i = 1, j = 0;

// Defining the lps array
int[] lps = new int[m];

while (i < m)
{

// If the ith index of string a matches with its jth index , then store the value j+1 at lps[i] and increment both i and j.
if (a.charAt(i) == a.charAt(j))
{
lps[i] = j + 1;

i++;

j++;
}

// If the ith index of a does not match with its jth index of a and j > 0, then j redirects to lps[j-1].
else if (j > 0)
{
j = lps[j - 1];
}

// If none of the above condition matches then make lps[i] as 0 and increment i.
else
{
lps[i] = 0;
i++;
}
}

i = 0;
j = 0;

//Iterating through both the strings to find a match
while (i < n && j < m)
{
// If the ith character of b matches with the jth character of a, then increment both i and j.
if (b.charAt(i) == a.charAt(j))
{
i++;
j++;
}

// If the above characters do not match and j > 0, then j redirects to lps[j-1].
else if (j > 0)
{
j = lps[j - 1];
}

// If none of the above mentioned condition matches, then increment i.
else
{
i++;
}
}

// If j is equal to m, then we will return 1 otherwise we will return 0
if (j == m)
{
return 1;
}
else
{
return 0;
}
}

public static int isCyclicRotation(String p, String q)
{
// Performing the concatenation of string p with itself
String res = p + p;

// Checking if the substring q is present in the string res
return isSubstring(q, res);
}
}

C++ (g++ 5.4)
/*
Time Complexity: O(N)
Space Complexity: O(N)

Where N denotes the length of both strings P and Q.
*/

// Function that checks whether string a is present in string b as substring using KMP algorithm
int isSubstring(string &a, string &b)
{
// Finding the length of both strings
int m = a.length();
int n = b.length();

// Defining and initializing the pointer variables to preprocess the string a
int i = 1, j = 0;

// Defining the lps array
int lps[m] = {0};

while (i < m)
{

// If the ith index of string a matches with its jth index , then store the value j+1 at lps[i] and increment both i and j.
if (a[i] == a[j])
{
lps[i] = j + 1;
i++;
j++;
}
// If the ith index of a does not match with its jth index of a and j > 0, then j redirects to lps[j-1].
else if (j > 0)
{
j = lps[j - 1];
}
// If none of the above condition matches then make lps[i] as 0 and increment i.
else
{
lps[i] = 0;
i++;
}
}

i = 0, j = 0;

//Iterating through both the strings to find a match
while (i < n && j < m)
{
// If the ith character of b matches with the jth character of a, then increment both i and j.
if (b[i] == a[j])
{
i++;
j++;
}
// If the above characters do not match and j > 0, then j redirects to lps[j-1].
else if (j > 0)
{
j = lps[j - 1];
}
// If none of the above mentioned condition matches, then increment i.
else
{
i++;
}
}

// If j is equal to m, then we will return 1 otherwise we will return 0
if (j == m)
{
return 1;
}
else
{
return 0;
}
}

int isCyclicRotation(string &p, string &q)
{
// Performing the concatenation of string p with itself
string res = p + p;

// Checking if the substring q is present in the string res
return isSubstring(q, res);
}

Python (3.5)
'''
Time Complexity: O(N)
Space Complexity: O(N)

Where N denotes the length of both strings P and Q.
'''

# Function that checks whether string a is present in string b as substring using KMP algorithm
def isSubstring(a, b):

# Finding the length of both strings
m = len(a)
n = len(b)

# Defining and initializing the pointer variables to preprocess the string a
i, j = 1, 0

# Defining the lps array
lps = [0 for i in range(m)]

while (i < m):

# If the ith index of string a matches with its jth index , then store the value j+1 at lps[i] and increment both i and j.
if (a[i] == a[j]):
lps[i] = j + 1
i += 1
j += 1

# If the ith index of a does not match with its jth index of a and j > 0, then j redirects to lps[j-1].
elif (j > 0):
j = lps[j - 1]

# If none of the above condition matches then make lps[i] as 0 and increment i.
else:
lps[i] = 0
i += 1

i, j = 0, 0

#Iterating through both the strings to find a match
while (i < n and j < m):

# If the ith character of b matches with the jth character of a, then increment both i and j.
if (b[i] == a[j]):
i += 1
j += 1

# If the above characters do not match and j > 0, then j redirects to lps[j-1].
elif (j > 0):
j = lps[j - 1]

# If none of the above mentioned condition matches, then increment i.
else:
i += 1

# If j is equal to m, then we will return 1 otherwise we will return 0
if (j == m):
return 1
else:
return 0


def isCyclicRotation(p, q):

# Performing the concatenation of string p with itself
res = p + p

# Checking if the substring q is present in the string res
return isSubstring(q, res)
Add answer anonymously...
Zopsmart Technology Full Stack Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter