String Rotation¶
A classic string problem that tests whether one string is a rotation of another, useful in cyclic data detection and sequence alignment tasks.
Problem¶
Given two strings s1 and s2, determine if s2 is a rotation of s1 using only one call to a substring check.
Example: s1 = "waterbottle", s2 = "erbottlewat", returns True.
Approach¶
The key insight: if you concatenate s1 with itself, every possible rotation of s1 appears as a contiguous substring. For "waterbottle", the doubled string "waterbottlewaterbottle" contains "erbottlewat" within it.
- Verify both strings have equal length and are non-empty (a rotation can't change the length).
- Concatenate
s1 + s1. - Check if
s2is a substring of the result.
Implementation¶
Complexity¶
- Time: O(n), string concatenation is O(n) and Python's
inoperator uses an optimized substring search. - Space: O(n), for the concatenated string.
Takeaway¶
The concatenation trick is one of those clever reductions that makes a hard-sounding problem trivial. Worth remembering anytime you're checking cyclic equivalence.