πDay 7. Strings Rotations of Each Other π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
You are given two strings of equal lengths, s1 and s2. The task is to check if s2 is a rotated version of s1.
Rotation means that the string s2 can be formed by shifting the characters of s1 cyclically.
Note: The characters in the strings are in lowercase.
π Example Walkthrough:
Input:
s1 = "abcd", s2 = "cdab"
Output:
true
Explanation:
After two right rotations, s1 becomes equal to s2.
Input:
s1 = "aab", s2 = "aba"
Output:
true
Explanation:
After one left rotation, s1 becomes equal to s2.
Input:
s1 = "abcd", s2 = "acbd"
Output:
false
Explanation: The strings are not rotations of each other.
Constraints:
$(1 \leq \text{s1.size(), s2.size()} \leq 10^5)$
π― My Approach:
String Concatenation and Substring Check:
The solution relies on the fact that a rotated version of
s1will always be a substring ofs1 + s1.By concatenating
s1with itself, all possible rotations ofs1are included in the resulting string.Then, we check if
s2is a substring of the concatenated string.
Edge Cases:
If the lengths of
s1ands2are different, they cannot be rotations.Strings with only one character are trivially rotations if they are equal.
Steps:
Check if the lengths of
s1ands2are equal.Concatenate
s1with itself to create a new string.Use efficient substring search techniques like
strstrorKMPto check ifs2is present in the concatenated string.
π Time and Auxiliary Space Complexity
Expected Time Complexity: (O(n)), where (n) is the length of the string. The concatenation takes (O(n)), and the substring search also runs in (O(n)) using algorithms like KMP.
Expected Auxiliary Space Complexity: (O(n)), as concatenating the string requires additional space for storing (s1 + s1).
π Solution Code
Code (C)
Code (Cpp)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated