Python 0796.py
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
return len(s) == len(goal) and (s + s).find(goal) != -1
Difficulty
and has an acceptance rate of about 67% (1+ million submissions).
Typical patterns to solve this problem:
- String
- String Matching
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The rotateString method determines whether one string can be transformed into another by performing a circular rotation. It receives two strings, s and goal, and returns a Boolean indicating if goal appears as a contiguous segment after any number of left-or-right shifts of s. The implementation leverages string concatenation and the built-in find operation to achieve this check in a concise manner.
Key Steps
The method first verifies that the two input strings share the same length, because a rotation cannot change the number of characters. This guard is expressed as a simple equality comparison:
len(s) == len(goal)
If the lengths match, the method constructs a new string by concatenating s with itself. This doubled string contains every possible rotation of s as a substring. The concatenation is performed with the + operator:
s + s
Finally, the method searches for goal inside the doubled string using the find method. The find call returns the index of the first occurrence or -1 if the substring is absent. The Boolean result of the comparison != -1 indicates whether a valid rotation exists:
(s + s).find(goal) != -1
The overall return statement combines the length check and the substring search with a logical and, ensuring that both conditions must be satisfied for a True result:
return len(s) == len(goal) and (s + s).find(goal) != -1
Edge Cases Handled
When both s and goal are empty strings, the length comparison evaluates to True (both lengths are zero). The concatenated string s + s also results in an empty string, and find on an empty string with an empty pattern returns 0, which is not -1. Consequently, the method correctly returns True, recognizing that an empty string is trivially a rotation of another empty string.
If s and goal have differing lengths, the length guard short-circuits the evaluation, and the method returns False without performing any concatenation or search. This prevents unnecessary work for mismatched inputs.
When goal is identical to s, the concatenated string contains s starting at index 0. The find operation locates goal immediately, and the method returns True, confirming that zero rotations satisfy the condition.
If goal appears multiple times within the doubled string, the find method still returns the index of the first occurrence, which is sufficient because any occurrence confirms the existence of a rotation. The method does not need to enumerate all possible positions.
Performance Optimizations
The implementation avoids explicit loops or repeated slicing, which would incur additional overhead. By using a single concatenation, it creates a representation that encodes all possible rotations in one contiguous block. The built-in find operation is highly optimized in CPython, often employing efficient algorithms such as Two-Way or Boyer-Moore under the hood, providing fast substring search even for large inputs.
The logical and short-circuits when the length check fails, preventing the potentially expensive concatenation and search for inputs that cannot be rotations due to size mismatch. This early exit contributes to overall efficiency, especially when processing many short strings where mismatched lengths are common.
ELI5 - Simplified Explanation
Imagine having a long train made of colored blocks. Each block is a letter. To see if one train can turn into the other, imagine glueing two of the first trains together into one very long train. If the second train is hiding somewhere inside that long double train, then it is possible to rearrange the first train to match the second one perfectly. The code first checks if both trains are the same length because they need to have the same number of blocks to match. Then, it looks inside that long double train to see if the second train exists in there.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Rust | Python | Go | PHP | TS | |||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| gouthampradhan | Java | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| Shamik07 | Dart | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| gouthampradhan | Java | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| ruoru | Rust | |||||||||||
| Shamik07 | Dart | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 783: Minimum Distance Between BST Nodes
- problem 393: UTF-8 Validation
- problem 787: Cheapest Flights Within K Stops
- problem 788: Rotated Digits
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality