Python Program to Check if Strings Are Rotation of Each Other
if len(s1) == len(s2) and s2 in s1 + s1.Examples
How to Think About It
Algorithm
Code
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
Dry Run
Let's trace the example where s1 = 'abcd' and s2 = 'cdab' through the code
Check length equality
len('abcd') == 4, len('cdab') == 4, so lengths are equal
Concatenate s1 with itself
'abcd' + 'abcd' = 'abcdabcd'
Check if s2 is substring
'cdab' in 'abcdabcd' is True
Return result
Function returns True
| Step | Operation | Value |
|---|---|---|
| 1 | Length check | 4 == 4 (True) |
| 2 | Concatenate s1 | 'abcdabcd' |
| 3 | Substring check | 'cdab' in 'abcdabcd' -> True |
| 4 | Return | True |
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
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
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
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Substring check (s2 in s1+s1) | O(n) | O(n) | Fast and simple for all cases |
| Manual rotation check | O(n²) | O(n) | Easy to understand but slower |
| Deque rotation | O(n²) | O(n) | Intuitive rotation but less efficient |