Split a String Into the Max Number of Unique Substrings - Problem
Split a String Into the Max Number of Unique Substrings
You're given a string
The Rules:
• You can split the string into any list of non-empty substrings
• When concatenated back together, these substrings must form the original string
• All substrings must be unique - no duplicates allowed!
• A substring is any contiguous sequence of characters
Goal: Return the maximum number of unique substrings you can create.
Example: For string
You're given a string
s, and your task is to split it into the maximum possible number of unique substrings. Think of it as cutting a rope into pieces where no two pieces can be identical!The Rules:
• You can split the string into any list of non-empty substrings
• When concatenated back together, these substrings must form the original string
• All substrings must be unique - no duplicates allowed!
• A substring is any contiguous sequence of characters
Goal: Return the maximum number of unique substrings you can create.
Example: For string
"ababccc", one optimal split could be ["a", "b", "ab", "c", "cc"] giving us 5 unique substrings. Input & Output
example_1.py — Basic Case
$
Input:
s = "ababccc"
›
Output:
5
💡 Note:
One optimal split is ["a", "b", "ab", "c", "cc"] which gives us 5 unique substrings. We could also do ["a", "ba", "b", "c", "cc"] for the same result.
example_2.py — Simple Case
$
Input:
s = "aba"
›
Output:
2
💡 Note:
We can split it as ["a", "ba"] or ["ab", "a"], both giving 2 unique substrings. We can't do ["a", "b", "a"] because "a" would be repeated.
example_3.py — All Same Characters
$
Input:
s = "aa"
›
Output:
1
💡 Note:
Since both characters are the same, we cannot split it into unique substrings. The only option is ["aa"], giving us 1 unique substring.
Constraints
- 1 ≤ s.length ≤ 16
- s contains only lowercase English letters
- Small constraint allows exponential solutions
Visualization
Tap to expand
Understanding the Visualization
1
Start with full string
We have "ababccc" and need to find the maximum unique splits
2
Try first cut
We can cut "a" or "ab" or "aba" etc. as the first piece
3
Recursively solve remainder
For each first piece, solve the remaining string optimally
4
Backtrack and try alternatives
Remove pieces from our used set and try different combinations
5
Find maximum
Keep track of the best solution found across all attempts
Key Takeaway
🎯 Key Insight: Backtracking with a hash set allows us to efficiently explore all possible string splits while avoiding duplicate substrings. The key is to add/remove substrings from our used set as we explore different paths, ensuring we find the maximum number of unique splits possible.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code