Split a String Into the Max Number of Unique Substrings — LeetCode 1593 Python Solution

MediumHash TableStringBacktracking
Problem
#1593
Reading time
4 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n^2 \times 2^n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview