Split a String Into the Max Number of Unique Substrings Problem
Description
LeetCode Problem 1593.
Given a string s, return the maximum number of unique substrings that the given string can be split into.
You can split string s into any list of non-empty substrings, where the concatenation of the substrings forms the original string. However, you must split the substrings such that all of them are unique.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "ababccc"
Output: 5
Explanation: One way to split maximally is ['a', 'b', 'ab', 'c', 'cc']. Splitting like ['a', 'b', 'a', 'b', 'c', 'cc'] is not valid as you have 'a' and 'b' multiple times.
Example 2:
Input: s = "aba"
Output: 2
Explanation: One way to split maximally is ['a', 'ba'].
Example 3:
Input: s = "aa"
Output: 1
Explanation: It is impossible to split the string any further.
Constraints:
1 <= s.length <= 16scontains only lower case English letters.
Solution
Approach: Backtracking with Pruning
With s.length <= 16 we can try every split. dfs(i) splits the suffix starting at i, while a set used holds the pieces chosen so far:
- If
i == n, the whole string is split; update the best count withlen(used). - Otherwise try every end
j > i. Ifs[i:j]is not inused, add it, recurse ondfs(j), then remove it again.
The pruning makes it fast: the remaining n - i characters can add at most n - i more pieces. If len(used) + (n - i) <= best, this branch cannot beat the answer we already have, so stop.
Greedy shortest pieces do not work: for "aba" it would give "a", "b", and then "a" again is a duplicate, so backtracking is needed.
Complexity: O(2n · n) time in the worst case (there are 2n-1 ways to cut the string and each piece costs O(n) to build and hash), and O(n) extra space besides the pieces in the set.
class Solution:
def maxUniqueSplit(self, s: str) -> int:
n = len(s)
used = set() # pieces of the current split
best = 0
def dfs(i: int) -> None:
nonlocal best
# even if every remaining character became its own piece, we could not beat best
if len(used) + (n - i) <= best:
return
if i == n:
best = len(used)
return
for j in range(i + 1, n + 1):
piece = s[i:j]
if piece not in used:
used.add(piece)
dfs(j)
used.remove(piece)
dfs(0)
return best