Open In App

Python – Check if two strings are Rotationally Equivalent

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Strings, we can have problem in which we need to check if one string can be derived from other upon left or right rotation. This kind of problem can have application in many domains such as web development and competitive programming. Let’s discuss certain ways in which this task can be performed.

Input : test_str1 = ‘GFG’, test_str2 = ‘FGG’ 
Output : True 

Input : test_str1 = ‘geeks’, test_str2 = ‘ksege’ 
Output : False

Method #1 : Using loop + string slicing The combination of above functions can be used to solve this problem. In this, we perform the task of extracting strings for performing all possible rotations, to check if any rotation equals the other string. 

Python3




# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
 
# initializing strings
test_str1 = 'geeks'
test_str2 = 'eksge'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# Check if two strings are Rotationally Equivalent
# Using loop + string slicing
res = False
for idx in range(len(test_str1)):
        if test_str1[idx: ] + test_str1[ :idx] == test_str2:
            res = True
            break
 
# printing result
print("Are two strings Rotationally equal ? : " + str(res))


Output : 

The original string 1 is : geeks
The original string 2 is : eksge
Are two strings Rotationally equal ? : True

Method #2 : Using any() + join() + enumerate() This is one of the ways in which this task can be performed. In this, we perform the task of checking any rotational equivalent using any() extracted using nested generator expression and enumerate(). 

Python3




# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
 
# initializing strings
test_str1 = 'geeks'
test_str2 = 'eksge'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# Check if two strings are Rotationally Equivalent
# Using any() + join() + enumerate()
res = any(''.join([test_str2[idx2 - idx1]
        for idx2, val2 in enumerate(test_str2)]) == test_str1
        for idx1, val1 in enumerate(test_str1))
 
# printing result
print("Are two strings Rotationally equal ? : " + str(res))


Output : 

The original string 1 is : geeks
The original string 2 is : eksge
Are two strings Rotationally equal ? : True

Time Complexity: O(n)
Space Complexity: O(n)

Method #3: Using the inbuilt() function to check if two strings are Rotationally Equivalent

Step-by-step algorithm:

  • Initialize two strings test_str1 and test_str2.
  • Concatenate test_str1 with itself and check if test_str2 is a substring of it.
  • If test_str2 is a substring of the concatenated string, then the strings are rotationally equivalent
  • Print the result.

Python3




test_str1 = 'geeks'
test_str2 = 'eksge'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# Check if two strings are Rotationally Equivalent
# Using inbuilt function
res = test_str2 in (test_str1+test_str1)
 
# printing result
print("Are two strings Rotationally equal ? : " + str(res))


Output

The original string 1 is : geeks
The original string 2 is : eksge
Are two strings Rotationally equal ? : True

Time complexity: O(n), where n is the length of the concatenated string.
Auxiliary Space: O(n), where n is the length of the concatenated string.

Method #4: Using string concatenation and string search

Step-by-step approach:

  • Initialize the two strings.
  • Concatenate the first string with itself.
  • Check if the second string is a substring of the concatenated string.
  • If the second string is a substring, then the two strings are rotationally equivalent.
  • Print the result.

Python3




# Python3 code to demonstrate working of
# Check if two strings are Rotationally Equivalent
# Using string concatenation and string search
 
# initializing strings
test_str1 = 'geeks'
test_str2 = 'eksge'
 
# printing original strings
print("The original string 1 is : " + str(test_str1))
print("The original string 2 is : " + str(test_str2))
 
# Check if two strings are Rotationally Equivalent
# Using string concatenation and string search
concat_str = test_str1 + test_str1
res = test_str2 in concat_str
 
# printing result
print("Are two strings Rotationally equal ? : " + str(res))


Output

The original string 1 is : geeks
The original string 2 is : eksge
Are two strings Rotationally equal ? : True

Time complexity: O(n), where n is the length of the strings.
Auxiliary space: O(n), where n is the length of the strings



Similar Reads

Find the Solidity and Equivalent Diameter of an Image Object Using OpenCV Python
In this article, we will see how we can find the solidity and the equivalent diameter of an object present in an image with help of Python OpenCV. Function to Find Solidity The solidity of an image is the measurement of the overall concavity of a particle. We can define the solidity of an object as the ratio of the contour area to its convex hull a
4 min read
Python | Find the equivalent discount in successive discounts in percentages
You are given n successive discounts in percentages. Your task is to find the equivalent discount in percentage. Input will contain a list in which each element of the list will be discount in percentage that will be negative in sign. Examples: Input : a = [-10, -35, -60, -75] Output : -94.14 Input : a = [-5, -20, -10.-23] Output : -49.08 SUCCESSIV
2 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
Python Program To Find Decimal Equivalent Of Binary Linked List
Given a singly linked list of 0s and 1s find its decimal equivalent. Input: 0->0->0->1->1->0->0->1->0 Output: 50 Input: 1->0->0 Output: 4 The decimal value of an empty linked list is considered as 0. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Initialize the result as 0. Traverse
2 min read
Python Program to Check if Two Strings are Anagram
Question: Given two strings s1 and s2, check if both the strings are anagrams of each other. Examples: Input : s1 = "listen" s2 = "silent" Output : The strings are anagrams. Input : s1 = "dad" s2 = "bad" Output : The strings aren't anagrams.Solution:Method #1 : Using sorted() function Python provides a inbuilt function sorted() which does not modif
5 min read
Python Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
8 min read
Python | Remove empty strings from list of strings
In many scenarios, we encounter the issue of getting an empty string in a huge amount of data and handling that sometimes becomes a tedious task. Let's discuss certain way-outs to remove empty strings from list of strings. Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this
7 min read
Python | Tokenizing strings in list of strings
Sometimes, while working with data, we need to perform the string tokenization of the strings that we might get as an input as list of strings. This has a usecase in many application of Machine Learning. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension + split() We can achieve this particular task using lis
3 min read
Python - Find all the strings that are substrings to the given list of strings
Given two lists, the task is to write a Python program to extract all the strings which are possible substring to any of strings in another list. Example: Input : test_list1 = ["Geeksforgeeks", "best", "for", "geeks"], test_list2 = ["Geeks", "win", "or", "learn"] Output : ['Geeks', 'or'] Explanation : "Geeks" occurs in "Geeksforgeeks string as subs
5 min read
Convert Strings to Numbers and Numbers to Strings in Python
In Python, strings or numbers can be converted to a number of strings using various inbuilt functions like str(), int(), float(), etc. Let's see how to use each of them. Example 1: Converting a Python String to an int: C/C++ Code # code # gfg contains string 10 gfg = "10" # using the int(), string is auto converted to int print(int(gfg)+2
2 min read
Practice Tags :
three90RightbarBannerImg