by Mike McGrath for In Easy Steps
When you need to establish whether a string of characters appears in any rotated order within another string, you can use the neat Doubling Trick to perform “cyclic rotation” testing. A cyclic rotation means taking a string, imagining its characters arranged in a loop, and then choosing a different starting point while keeping the order unchanged. Picture the string written around a circle:
Reading from each position produces:
- From (a): a, b, c, d -> “abcd”
- From (b): b, c, d, a -> “bcda”
- From (c): c, d, a, b -> “cdab”
- From (d): d, a, b, c -> “dabc”
This is cyclic rotation.
The products “abcd”, “bcda”, “cdab”, “dabc” are all valid rotations, but identical strings are not rotations.
Using the Doubling Trick to turn “abcd” into “abcdabcd” creates a straight sequence long enough to include every wrap‑around reading from the circular version of the string. Any valid rotation (such as “bcda”, “cdab”, “dabc”) appears somewhere inside this doubled sequence.
If a query string is a rotation of a source string, then query must appear inside source + source.
This provides a minimal, loop‑free, index‑free test. For example…
def is_rotation(source, query):
# Different lengths cannot be rotations.
if len(source) != len(query):
return False
# Doubling trick.
return query in (source + source)
print(is_rotation(“abcd”, “bcda”))
print(is_rotation(“abcd”, “dabc”))
print(is_rotation(“abcd”, “acbd”))
Post Views: 0