#63 π 796. Rotate String π§ π
Imagine you have two strings, s and goal, and you want to know if you can rotate s some number of times so it matches goal. Letβs dive into how to solve this with some cool insights and a clean algorithm! πβ¨
π Problem Statement
Given two strings s and goal, your task is to check if s can be rotated to become goal. A rotation (or shift) moves the first character of s to the last position. If we perform enough rotations on s, we may or may not match goal.
Constraints:
1 <= s.length, goal.length <= 100- Both
sandgoalconsist of lowercase English letters.
π§© Example Scenarios
Example 1
Input:
s = "abcde"
goal = "cdeab"
Output:
True
Explanation:
After rotating s twice, it becomes "cdeab", which matches goal!
Example 2
Input:
s = "abcde"
goal = "abced"
Output:
False
Explanation:
No amount of rotation on s can turn it into goal.
π οΈ Solution Approaches
πΆ Basic Solution (Intuitive Approach)
The most intuitive way to solve this is by rotating the string s manually and checking if it ever matches goal.
- Initialize by checking if
sandgoalhave the same length. If not, returnFalse. - Rotate
sby moving its first character to the end, and check if this equalsgoal. - Repeat until we either find a match or exhaust all possible rotations.
This approach is straightforward, but it may not be optimal for larger strings. Letβs analyze its time complexity.
π Time Complexity of Basic Solution
For each rotation, we compare s with goal, which takes O(n) time. If we perform n rotations, the overall time complexity becomes O(n^2).
Python Code (Basic Solution)
def rotate_string(s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
# Try all rotations
for i in range(len(s)):
# Rotate by slicing
rotated = s[i:] + s[:i]
if rotated == goal:
return True
return False
π Optimized Solution (Concatenate Trick)
Letβs optimize our approach with a clever trick! Instead of rotating s multiple times, consider the concatenation of s with itself. When s is doubled (i.e., s + s), it contains all possible rotations of s as its substrings. For example:
- If
s = "abcde", thens + s = "abcdeabcde"contains rotations like"bcdea","cdeab", etc.
With this trick, our solution simplifies to just checking if goal is a substring of s + s.
Steps:
- Check Lengths: If
sandgoaldonβt have the same length, returnFalse. - Concatenate
swith itself: Create a new stringdoubled_s = s + s. - Check if
goalis a substring ofdoubled_s: If it is, thenscan be rotated to matchgoal.
π Time Complexity of Optimized Solution
This approach takes O(n) to create doubled_s and O(n) to check if goal is a substring of doubled_s, so the overall complexity is O(n).
Python Code (Optimized Solution)
def rotate_string(s: str, goal: str) -> bool:
if len(s) != len(goal):
return False
doubled_s = s + s
return goal in doubled_s
π Example Walkthrough
Letβs go through an example to see this solution in action.
Walkthrough Example (Larger String)
Input
s = "abcdefg"
goal = "efgabcd"
-
Concatenate
swith itself:
doubled_s = "abcdefgabcdefg" - Check if
goalis indoubled_s:doubled_scontains all rotations ofs.- Since
goal = "efgabcd"is a substring ofdoubled_s, we can confirm thatscan be rotated to becomegoal.
- Return Result:
Sincegoalis indoubled_s, we returnTrue.
π§ͺ Edge Cases
- Different Lengths: If
sandgoalhave different lengths, returnFalse. - Identical Strings: If
sandgoalare already the same, returnTrue. - Single Character Strings: If
sandgoalare both one character and identical, returnTrue; otherwise, returnFalse. - No Possible Rotation: If
goalis a unique combination that doesnβt appear indoubled_s, returnFalse.
π‘ Conclusion
In this problem, we explored two different approaches to determine if a string can be rotated to match another string:
- Basic Solution: Manually rotating and comparing, which has
O(n^2)complexity. - Optimized Solution: Using the concatenation trick, which simplifies the problem to a substring search with
O(n)complexity.
The concatenation method is clearly the more efficient solution. This technique of concatenating a string with itself is a powerful tool for rotation-based problems.
π Summary
This problem highlights the beauty of thinking creatively in codingβby realizing that every possible rotation of s is hidden within s + s, we unlock an optimized solution thatβs both elegant and efficient. Try applying this trick to other rotation problems, and see the magic! β¨