#1593
Split a String Into the Max Number of Unique Substrings
MediumHash TableStringBacktrackingHash MapBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 2^n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * 2^n)Space O(n)
The optimal solution uses backtracking with memoization to avoid recalculating results for the same starting index and set of used substrings. This significantly reduces the number of computations and improves efficiency.
⚙️
Algorithm
3 steps- 1Step 1: Use a recursive function with memoization to store results for each starting index.
- 2Step 2: At each index, try all possible substrings and track unique ones using a set.
- 3Step 3: Return the maximum count of unique substrings found.
solution.py17 lines
1# Full working Python code
2from typing import Set
3from functools import lru_cache
4
5class Solution:
6 def maxUniqueSplit(self, s: str) -> int:
7 @lru_cache(None)
8 def backtrack(start: int, used: frozenset) -> int:
9 if start == len(s):
10 return len(used)
11 max_count = 0
12 for end in range(start + 1, len(s) + 1):
13 substring = s[start:end]
14 if substring not in used:
15 max_count = max(max_count, backtrack(end, used | {substring}))
16 return max_count
17 return backtrack(0, frozenset())ℹ
Complexity note: The time complexity is O(n * 2^n) due to the exponential number of subsets of substrings we can create, but memoization helps reduce redundant calculations. The space complexity is O(n) for storing the memoization map.
- 1Using a set helps track uniqueness efficiently.
- 2Backtracking allows exploring all combinations while pruning invalid paths.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.