Python Program to Check String Rotation

String rotation is a common problem where we check if one string can be obtained by rotating another string.

This problem helps in understanding string manipulation, substring checking, and pattern matching.

1. Understanding the Problem

Given two strings, check if one is a rotation of the other.

Input: s1 = "abcd", s2 = "cdab"
Output: True

2. Method 1: Using Concatenation

Python
Concatenation method
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")

if len(s1) == len(s2) and s2 in (s1 + s1):
    print("Rotation")
else:
    print("Not Rotation")

If s2 is a substring of s1+s1, then it is a rotation.

3. Method 2: Using Loop

Python
Manual rotation check
s1 = input()
s2 = input()

is_rotation = False

for i in range(len(s1)):
    rotated = s1[i:] + s1[:i]
    if rotated == s2:
        is_rotation = True
        break

print(is_rotation)

This method generates all rotations and compares them.

4. Method 3: Using Function

Python
Reusable function
def is_rotation(s1, s2):
    return len(s1) == len(s2) and s2 in (s1 + s1)

print(is_rotation("abcd", "cdab"))

Encapsulating logic in a function improves readability.

5. Method 4: Using collections.deque

Python
Using deque rotation
from collections import deque

s1 = input()
s2 = input()

d = deque(s1)

for _ in range(len(s1)):
    d.rotate(1)
    if ''.join(d) == s2:
        print(True)
        break
else:
    print(False)

Deque allows efficient rotation operations.

6. Method 5: Handling Edge Cases

Python
Edge case handling
s1 = input().strip()
s2 = input().strip()

if not s1 and not s2:
    print(True)
elif len(s1) != len(s2):
    print(False)
else:
    print(s2 in (s1 + s1))

Handles empty strings and length mismatches safely.

7. Algorithm

1. Take two input strings.

2. Check if lengths are equal.

3. Concatenate first string with itself.

4. Check if second string is a substring.

5. Return result.

8. Common Mistakes

1. Not checking string lengths.

2. Incorrect substring logic.

3. Ignoring empty strings.

4. Using inefficient brute force unnecessarily.

9. Applications

1. String matching problems.

2. Circular data structures.

3. Pattern recognition.

4. Interview coding questions.

Conclusion

String rotation is a classic problem that demonstrates the power of string concatenation and pattern matching.

The concatenation method is the most efficient and commonly used approach.