Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check String Rotation

Check whether one string is a rotation of another with Python. Students require equal lengths and search the doubled first string for a wrapped arrangement.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 10 of 14
check-string-rotation.py
1# Take two strings
2s1 = input("Enter first string: ")
3s2 = input("Enter second string: ")
4
5# Check rotation
6if len(s1) == len(s2):
7 # Concatenate s1 with itself
8 temp = s1 + s1
9 if s2 in temp:
10 print("Rotation")
11 else:
12 print("Not a rotation")
13else:
14 print("Not a rotation (different lengths)")

Output

Enter first string: hello
Enter second string: lohel
Rotation

In this one

  • Preserve rotation length
  • Search doubled text
  • Allow zero-position rotation

How it works

  1. 1

    Compare the two string lengths.

  2. 2

    When equal, build s1 + s1.

  3. 3

    Test membership of s2 and print the rotation decision.

Edge cases

Do identical strings count as rotations?

Do identical strings count as rotations?

Yes. A zero-position rotation is allowed.

Why compare lengths first?

Why compare lengths first?

A rotation preserves the number of characters.

What's going on

Joining s1 to itself makes every cyclic starting point appear as a contiguous substring. The length guard ensures s2 represents a full rotation, not a shorter fragment.

For abcd and cdab, the doubled text abcdabcd contains cdab. This allows a zero-position rotation, so identical strings pass. Matching is exact and case-sensitive; even two empty strings pass the length and substring checks.

Do identical strings count as rotations? Yes. A zero-position rotation is allowed.

Why compare lengths first? A rotation preserves the number of characters.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which construction supports wrapped matches?

Pick an answer to check it.

Question 2

Do identical strings count as rotations?

Pick an answer to check it.

Questions people ask

Do identical strings count as rotations?

Yes. A zero-position rotation is allowed.

Why compare lengths first?

A rotation preserves the number of characters.

Which construction supports wrapped matches?

s1 + s1.