In Easy Steps Articles

July 3, 2026

Python tip: The Doubling Trick – in easy steps

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”))

 

 

 

Sign up to our

Newsletter

Our newsletters inform you of new and forthcoming titles, handy tips, and other updates and special offers. You can opt out anytime.

"*" indicates required fields

By In Easy Steps Team

Share

We are sorry to let you go...

Would you mind giving us your feedback or reason of cancelling the subscription?

 

"*" indicates required fields

This field is hidden when viewing the form
This field is hidden when viewing the form
This field is hidden when viewing the form
Reason For Cancellation*
This field is hidden when viewing the form