Split a String Into the Max Number of Unique Substrings — LeetCode 1593 Python Solution
- Problem
- #1593
- Pattern
- Backtracking
- Reading time
- 4 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def maxUniqueSplit(self, s: str) -> int:
def dfs(i: int):
nonlocal ans
if len(st) + len(s) - i <= ans:
return
if i >= len(s):
ans = max(ans, len(st))
return
for j in range(i + 1, len(s) + 1):
if s[i:j] not in st:
st.add(s[i:j])
dfs(j)
st.remove(s[i:j])
ans = 0
st = set()
dfs(0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times 2^n) |
| Space | O(n) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1593. Split a String Into the Max Number of Unique Substrings is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1593. Split a String Into the Max Number of Unique Substrings?
- LeetCode 1593. Split a String Into the Max Number of Unique Substrings is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1593. Split a String Into the Max Number of Unique Substrings?
- The Python solution on this page runs in O(n^2 \times 2^n).
- What is the space complexity of LeetCode 1593. Split a String Into the Max Number of Unique Substrings?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1593. Split a String Into the Max Number of Unique Substrings cover?
- LeetCode 1593. Split a String Into the Max Number of Unique Substrings is tagged Hash Table, String and Backtracking on LeetCode.