Check If One String Is a Rotation of Another

Hard ⏱ 18 min 35% acceptance ★★★★★ 4.5
Write is_rotation(s1, s2) that returns True if s2 is a rotation of s1 (i.e. s2 can be produced by moving some prefix of s1 to its end), using only a single substring-containment check — no manual rotation loop.

Examples

Example 1
Input
s1 = 'waterbottle', s2 = 'erbottlewat'
Output
True
Explanation

Rotating 'waterbottle' by moving 'wat' to the end gives 'erbottlewat'.

Example 2
Input
s1 = 'hello', s2 = 'lohel'
Output
True
Explanation

Moving 'hel' to the end of 'hello' gives 'lohel'.

Example 3
Input
s1 = 'hello', s2 = 'olelh'
Output
False
Explanation

Not a valid rotation — letters in the wrong relative order.

Constraints

  • s1 and s2 must be the same length to possibly be rotations; otherwise return False immediately.

Topics

StringsSubstring Search

Companies

MicrosoftAppleUber

Hints

Hint 1

Every rotation of s1 is a substring of `s1 + s1`.

Hint 2

So `s2 in (s1 + s1)` (after checking equal lengths) answers the question in one line.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.