Check if One String is Rotation of Another
Problem Statement:β
You are given two strings of equal lengths,Β s1Β andΒ s2. The task is to checkΒ ifΒ s2Β is a rotated version of the stringΒ s1.
Note:Β The characters in the strings are in lowercase.
-
Example:
Input: s1 = "abcd", s2 = "cdab"
Output: true
Explanation: After 2 right rotations, s1 will become equal to s2.
Input: s1 = "aab", s2 = "aba"
Output: true
Explanation: After 1 left rotation, s1 will become equal to s2.
Input: s1 = "abcd", s2 = "acbd"
Output: false
Explanation: Strings are not rotations of each other.
β Solution 1: Brute Force Rotation Checkβ
class Solution {
public:
bool areRotations(string &s1, string &s2) {
for(int i = 0; i < s1.size(); i++){
string prefix = s1.substr(i) + s1.substr(0, i); // Rotate string
if(prefix == s2)
return true;
}
return false;
}
};
π How It Worksβ
- For each index
ifrom0tos1.length() - 1, you simulate a rotation ofs1by moving the prefixs1.substr(0, i)to the end. - If any such rotation matches
s2, returntrue. - If no rotation matches, return
false.
π§© Key Conceptβ
You are generating all n possible rotations of s1 and comparing them with s2.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(nΒ²) |
| Space | O(n) |
Due to repeated string slicing and concatenation.
β οΈ Edge Casesβ
- Unequal lengths β return
falseimmediately. - Identical strings β return
true(rotation by 0). - Empty strings β return
true(conventionally).
β Solution 2: Concatenation Trick (Optimal)β
class Solution {
public:
bool areRotations(string &s1, string &s2) {
return (s1.size() == s2.size()) && ((s1 + s1).find(s2) != string::npos);
}
};
π How It Worksβ
- If
s2is a rotation ofs1, then it must be a substring ofs1 + s1. - For example,
"ABCD"and"CDAB"β"ABCDABCD"contains"CDAB".
π§© Key Conceptβ
- If
s2is a rotation ofs1, it must appear in the concatenated strings1 + s1.
β±οΈ Time & Space Complexityβ
| Metric | Value |
|---|---|
| Time | O(n) |
| Space | O(n) |
Using .find() is optimized and avoids redundant comparisons.
β οΈ Edge Casesβ
- Check for length mismatch first β if lengths are unequal, it cannot be a valid rotation.
π‘ Other Approachesβ
| Method | Time | Space | Notes |
|---|---|---|---|
| Brute-force Rotation | O(nΒ²) | O(n) | Simulates each rotation |
| Concatenation + Find | O(n) | O(n) | Optimal and elegant β |
π Related Problemsβ
π Level Up Your Engineering Mindset
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Official Hub
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.