Python 1593.py
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def deeper(start, have):
if start == len(s):
print(have)
return 0
best = 0
for end in range(start + 1, len(s) + 1): # point beyond last element
sub = s[start : end]
if sub in have:
continue
have.add(sub)
best = max(best, 1 + deeper(end, have))
have.discard(sub) # allows re-using this set() again
return best
return deeper(0, set())
Difficulty
and has an acceptance rate of about 69% (200k+ submissions).
Typical patterns to solve this problem:
- Backtracking
- Hash Table
- String
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 provided implementation solves the problem of partitioning a string into the maximum number of substrings such that each substring is unique. It employs a depth-first search with backtracking, exploring every possible split while maintaining a set of substrings that have already been used in the current branch. The recursion terminates when the end of the input string is reached, at which point the current collection of unique substrings is printed for diagnostic purposes.
Entry Point
The public method maxUniqueSplit receives the input string s and immediately invokes the nested helper deeper with an initial index of 0 and an empty set to track used substrings.
def maxUniqueSplit(self, s: str) -> int:
return deeper(0, set())
Recursive Helper Definition
Inside maxUniqueSplit, the function deeper(start, have) is defined. The parameter start marks the current position in the string, while have is a mutable set that holds all substrings selected so far in the current recursion path.
def deeper(start, have):
Base Case
When start equals the length of the string, the recursion has successfully consumed the entire input. The current set of substrings is printed, and the function returns 0 because no further splits can be made beyond this point.
if start == len(s):
print(have)
return 0
Exploration Loop
The core of the algorithm iterates over every possible end position for the next substring, ranging from start + 1 up to len(s) + 1. The slice s[start:end] yields the candidate substring.
for end in range(start + 1, len(s) + 1):
sub = s[start:end]
Duplicate Detection
Before committing to a candidate, the code checks whether the substring already exists in the have set. If it does, the loop skips this candidate, ensuring that only unique substrings are considered.
if sub in have:
continue
State Update and Recursive Descent
When a new unique substring is found, it is added to the set, and the recursion proceeds from the new index end. The result of the recursive call is incremented by 1 to account for the newly added substring, and the maximum value across all candidates is retained in best.
have.add(sub)
best = max(best, 1 + deeper(end, have))
Backtracking
After the recursive call returns, the substring is removed from the set using discard. This step restores the set to its prior state, allowing the algorithm to explore alternative split configurations that do not include the current substring.
have.discard(sub)
Result Propagation
When the loop finishes, the function returns the best count found for the current start position. This value propagates back up the recursion stack, ultimately yielding the maximum number of unique substrings for the entire string.
return best
Edge Cases Handled
The algorithm gracefully handles an empty input string. In that scenario, the initial call to deeper receives start == 0 and len(s) == 0, triggering the base case immediately, printing an empty set, and returning 0.
When the input consists of a single repeated character (e.g., "aaaa"), the only viable split that respects uniqueness is the entire string itself. The loop will generate substrings of increasing length, but as soon as a shorter substring is added to the set, any later identical substring will be rejected by the duplicate detection, forcing the recursion to backtrack and eventually settle on the longest possible unique segment.
If the string contains many overlapping repeated patterns, the set-based duplicate check ensures that the algorithm never reuses a substring within the same branch, preventing infinite loops and guaranteeing termination even in highly repetitive inputs.
The diagnostic print(have) in the base case provides visibility into the exact composition of the unique split that leads to a terminal state, which can be useful for verifying correctness on edge inputs.
Performance Optimizations
The use of a Python set for have provides constant-time membership tests (sub in have) and constant-time removal (have.discard(sub)). This choice eliminates the need for linear scans over previously selected substrings, which would otherwise degrade performance as the depth of recursion grows.
By inserting the substring into the set before the recursive call and discarding it immediately after, the algorithm reuses the same mutable set object throughout the entire search space. This avoids the overhead of allocating a new set at each recursion level, reducing memory churn and improving cache locality.
The loop iterates only over forward extensions of the current start index, guaranteeing that each possible substring is examined exactly once per branch. The early continue on duplicate detection prevents unnecessary recursive invocations for substrings that cannot contribute to a valid solution, pruning large portions of the search tree when repeated patterns are present.
Finally, the recursive return value is computed as 1 + deeper(end, have), allowing the algorithm to accumulate the count incrementally without constructing auxiliary data structures to track the split composition. This in-place accumulation keeps the runtime footprint minimal while still exploring the full combinatorial space.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful building blocks all connected in a line. This code is like a game where you want to chop the string into as many smaller pieces as possible, but there is one rule: every piece you cut off must look different from the others.
The computer starts at the very beginning of the line and tries taking a tiny chunk of the blocks. It remembers this chunk by putting it into a special collection. Then, it looks at the rest of the string and tries to chop it up again.
Because the computer wants to find the biggest number of pieces, it tries out every single way to chop the line. If it picks a piece that it has already used before, it knows that path will not work, so it stops and tries a different size for that chunk instead. It keeps trying different sizes for all the chunks until it finds the best way to slice the whole thing into the most unique parts. Once it finishes exploring all the different options, it knows exactly how many chunks the line can be split into.
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 | |||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||
| Progiez | C++ | Java | Python | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| keineahnung2345 | C++ | ||||||
| lkwq007 | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1442: Count Triplets That Can Form Two Arrays of Equal XOR
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1726: Tuple with Same Product
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
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