0
0
PythonProgramBeginner · 2 min read

Python Program to Check if Strings Are Rotation of Each Other

You can check if two strings are rotations of each other by verifying if one string is a substring of the other string repeated twice, using if len(s1) == len(s2) and s2 in s1 + s1.
📋

Examples

Inputs1 = 'abcd', s2 = 'cdab'
OutputTrue
Inputs1 = 'hello', s2 = 'llohe'
OutputTrue
Inputs1 = 'abc', s2 = 'acb'
OutputFalse
🧠

How to Think About It

To check if one string is a rotation of another, first ensure both strings have the same length. Then imagine joining the first string to itself; if the second string appears anywhere inside this doubled string, it means the second string is a rotation of the first.
📐

Algorithm

1
Get two input strings s1 and s2
2
Check if lengths of s1 and s2 are equal; if not, return False
3
Create a new string by concatenating s1 with itself
4
Check if s2 is a substring of the new concatenated string
5
Return True if it is, otherwise return False
💻

Code

python
def are_rotations(s1, s2):
    if len(s1) != len(s2):
        return False
    return s2 in s1 + s1

# Example usage
print(are_rotations('abcd', 'cdab'))  # True
print(are_rotations('hello', 'llohe'))  # True
print(are_rotations('abc', 'acb'))  # False
Output
True True False
🔍

Dry Run

Let's trace the example where s1 = 'abcd' and s2 = 'cdab' through the code

1

Check length equality

len('abcd') == 4, len('cdab') == 4, so lengths are equal

2

Concatenate s1 with itself

'abcd' + 'abcd' = 'abcdabcd'

3

Check if s2 is substring

'cdab' in 'abcdabcd' is True

4

Return result

Function returns True

StepOperationValue
1Length check4 == 4 (True)
2Concatenate s1'abcdabcd'
3Substring check'cdab' in 'abcdabcd' -> True
4ReturnTrue
💡

Why This Works

Step 1: Length must be equal

If two strings have different lengths, they cannot be rotations of each other, so we check len(s1) == len(s2) first.

Step 2: Double the first string

Concatenating s1 + s1 creates a string that contains all possible rotations of s1 as substrings.

Step 3: Check substring presence

If s2 is found inside s1 + s1, it means s2 is a rotation of s1.

🔄

Alternative Approaches

Manual rotation check
python
def are_rotations_manual(s1, s2):
    if len(s1) != len(s2):
        return False
    for i in range(len(s1)):
        rotated = s1[i:] + s1[:i]
        if rotated == s2:
            return True
    return False

print(are_rotations_manual('abcd', 'cdab'))  # True
This method checks each possible rotation by slicing and comparing, which is less efficient but easy to understand.
Using collections.deque rotation
python
from collections import deque

def are_rotations_deque(s1, s2):
    if len(s1) != len(s2):
        return False
    d = deque(s1)
    for _ in range(len(s1)):
        d.rotate(1)  # rotate right by 1
        if ''.join(d) == s2:
            return True
    return False

print(are_rotations_deque('abcd', 'cdab'))  # True
This uses a double-ended queue to rotate characters, which is intuitive but slower than substring check.

Complexity: O(n) time, O(n) space

Time Complexity

Checking substring with s2 in s1 + s1 takes O(n) time where n is the length of the strings.

Space Complexity

Concatenating s1 + s1 creates a new string of length 2n, so space complexity is O(n).

Which Approach is Fastest?

The substring check method is fastest and simplest compared to manual rotation or deque rotation which take O(n²) time.

ApproachTimeSpaceBest For
Substring check (s2 in s1+s1)O(n)O(n)Fast and simple for all cases
Manual rotation checkO(n²)O(n)Easy to understand but slower
Deque rotationO(n²)O(n)Intuitive rotation but less efficient
💡
Always check string lengths first to quickly rule out impossible rotations.
⚠️
Forgetting to check if strings have the same length before checking rotations.