Understanding the Problem
We are given two strings, s1
and s2
, and our task is to determine whether s2
is a rotation of s1
. A rotation means that the characters in s1
can be moved around in a circular fashion to form s2
.
For example, if s1 = "waterbottle"
, then any of the following are valid rotations: "erbottlewat"
, "lewaterbott"
, "ottlewaterb"
, etc.
A beginner-friendly way to think about it is: you can "cut" s1
at any position and swap the two parts — if you get s2
, then it's a rotation.
Step-by-Step Solution with Example
step 1: Check Lengths
If two strings are not of the same length, they can never be rotations of each other. So, the first check should be:
if (s1.length !== s2.length) return false;
step 2: Concatenate s1 with itself
The key trick is this: If you take s1
and concatenate it with itself (s1 + s1
), all possible rotations of s1
will be included in this new string.
let combined = s1 + s1;
step 3: Check if s2 is a substring of combined
Now we simply check whether s2
is a substring of combined
. If it is, then s2
is a rotation of s1
.
return combined.includes(s2);
step 4: Try with a Real Example
Let’s say s1 = "waterbottle"
and s2 = "erbottlewat"
.
- Step 1: Length check – both are length 11 ✅
- Step 2: Concatenate
s1
with itself – "waterbottlewaterbottle"
- Step 3: Check if
s2
is a substring of the above – Yes, it is! ✅
So the output will be true
.
Edge Cases
- Case 1: Same strings – If
s1 = s2
, then it's a rotation (rotation by 0 characters).
- Case 2: Valid rotation –
s2
can be formed by rotating characters from the front of s1
to the back.
- Case 3: Different lengths – Return
false
immediately.
- Case 4: Same length, different characters – Even with equal lengths, mismatched content will return
false
.
- Case 5: Empty strings – Two empty strings are considered valid rotations. Return
true
.
- Case 6: One string empty – If only one is empty, return
false
.
Finally
This solution is elegant, beginner-friendly, and efficient. It avoids manual rotation checks and uses string operations that are optimized in modern programming languages.
Time Complexity: O(n) — for substring search
Space Complexity: O(n) — due to the concatenated string
The core idea — doubling the string to expose all rotations — is a clever trick worth remembering.
Comments
Loading comments...