Split a String Into the Max Number of Unique Substrings

DFS partition of the string trying every prefix; track a set of already-used substrings.

Medium
Time O(2^n * n) Space O(n)
LeetCode
4 min read
backtracking string

Problem#

Split s into substrings such that all substrings are unique. Return the maximum number of pieces.

Examples#

  • s = "ababccc"5 ("a","b","ab","c","cc")

Constraints#

  • 1 <= s.length <= 16.

Approach#

DFS over partition points. Maintain a set of used substrings. For each prefix not already used, take it and recurse on the remainder.

Solution#

Max Unique Splits
class Solution {
public:
int maxUniqueSplit(string s) {
int best = 1;
unordered_set<string> used;
function<void(int,int)> dfs = [&](int i, int cnt) {
if (cnt + (int)(s.size() - i) <= best) return; // prune
if (i == (int)s.size()) { best = max(best, cnt); return; }
for (int j = i + 1; j <= (int)s.size(); ++j) {
string piece = s.substr(i, j - i);
if (used.insert(piece).second) {
dfs(j, cnt + 1);
used.erase(piece);
}
}
};
dfs(0, 0);
return best;
}
};

Editorial#

Pruning is essential: if even the maximum possible additional splits (one char each) can’t beat the current best, skip. Hash-set insertion’s “did we already have this?” check is folded into .second.

Complexity#

  • Time: O(2^n * n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.