Break a String Into Maximum Number of Unique Substrings
Cut a string into as many pieces as possible so that no two pieces are the same.
Given a string s
Example 1
Output: 5
Explanation: one way is ["a", "b", "ab", "c", "cc"].
Example 2
Output: 2
Explanation: for example ["a", "ba"]. Splitting into "a", "b", "a" would repeat "a".
The Idea
Think of the string as a strip of paper with letters printed on it. You cut the strip into pieces, and no two pieces may read the same. The more pieces, the better.
Take Example 1, "ababccc". Cutting after every letter gives seven pieces, a, b, a, b, c, c and c, but "a" appears twice, and so do "b" and "c". The answer keeps every piece new by letting some of them grow: a, b, ab, c and cc. That makes five pieces, all different.
How do we decide where to cut? A natural rule is to always cut the shortest piece that is still new. On "ababccc" that rule gives exactly a, b, ab, c and cc. Now try it on "aaba". It cuts "a", then "ab", and only "a" is left, which is already used. The rule gets stuck, yet "aa", "b", "a" is a cut with three different pieces.
So a cut made early changes which pieces are allowed later, and no simple rule can tell which cut will pay off. The safe way is to try every possible first piece and, for each one, cut what is left the same way, remembering which pieces are used.
Look at the picture below, which does that for Example 2, "aba". Each box shows the part of the string still left to cut and the pieces used so far.
The top box has all of "aba" left and nothing used. Its three lines try the three possible first pieces: cut "a", cut "ab" and cut "aba". Follow the orange path. After cut "a", the box shows "ba" left and "a" used. From there, the grey line cut "b" leaves "a", which is used, so it ends in the dashed box labelled dead end. The orange line cut "ba" gives 2 pieces instead.
The teal path, cut "ab" and then cut "a", also gives 2 pieces, and cutting the whole "aba" gives 1. So the answer is 2. Notice the teal box under cut "ab": it says "used: ab" only. The "a" from the orange path was taken back before the search tried "ab", so it no longer blocks anything.
Making a choice, exploring everything that follows from it, and taking the choice back before trying the next one is called backtracking.
Solution Approach
Turning that search into code means settling four things: how it compares with listing every possible cut, which pieces to try at each position, how to keep track of the used pieces, and what a dead end returns.
Listing every possible cut
Why not list every way to cut the string and keep the best one without repeats? Between two neighbouring letters we either cut or we do not. A string of n letters has n - 1 such gaps, so it can be cut in 2n - 1 ways: 4 ways for "aba", and 32,768 for 16 letters.
The search in the picture walks through the same cuts, but it drops a path as soon as a piece repeats, as the dead end shows. It never finishes a cut that is already broken. Either way the work doubles with each extra letter, and the limit of 16 letters is what keeps it affordable.
Which pieces to try
Say the search has cut everything before position startstart
Each of these pieces that is not used yet is a candidate. For a candidate, the search finds the most pieces for the rest of the string, from where the candidate ends, and adds 1 for the candidate itself. The best candidate gives the answer for startstart
Keeping track of the used pieces
How does the search know which pieces are used? A HashSet<String>addfalse
Once the rest of the string has been explored, remove
What a dead end returns
What should the search return when every possible next piece is already used, as at the bottom of the picture? Not 0, because 0 means the rest was cut completely. The search returns -1 instead, and a candidate counts only when the rest gave 0 or more. A path that ends in a dead end is then never counted as a cut.
Java Solution
The method maxUniqueSplitsplit
- First,
starts the search withmaxUniqueSplit : position 0, and an empty setsplit(s, 0, new HashSet<>()) for the pieces taken so far.used - In
, ifsplit equalsstart , nothing is left to cut, so it returns 0.s.length() - Otherwise,
starts at -1, meaning no cut of the rest has been found yet. A loop movesbest fromend tostart + 1 , ands.length() is the candidate frompiece = s.substring(start, end) up to, but not including,start .end - If
returnsused.add(piece) , the piece is new. The recursive calltrue finds the most pieces for the rest and stores it insplit(s, end, used) . Ifrest is 0 or more,rest becomes the larger ofbest andbest . Then1 + rest takes the piece back.used.remove(piece) - After the loop,
returnssplit , which is still -1 if every candidate was used or led to a dead end.best
The main
import java.util.HashSet;
import java.util.Set;
public class BreakAStringIntoMaximumUniqueSubstrings {
public static int maxUniqueSplit(String s) {
return split(s, 0, new HashSet<>());
}
// Most pieces for s[start..] when the pieces in 'used' are already taken
private static int split(String s, int start, Set<String> used) {
if (start == s.length()) {
return 0; // nothing left to cut
}
int best = -1; // -1: no valid split of the rest
for (int end = start + 1; end <= s.length(); end++) {
String piece = s.substring(start, end);
if (used.add(piece)) { // choose this piece if it is new
int rest = split(s, end, used);
if (rest >= 0) {
best = Math.max(best, 1 + rest);
}
used.remove(piece); // take the piece back
}
}
return best;
}
public static void main(String[] args) {
System.out.println(maxUniqueSplit("ababccc"));
System.out.println(maxUniqueSplit("aba"));
System.out.println(maxUniqueSplit("aaba"));
System.out.println(maxUniqueSplit("a"));
System.out.println(maxUniqueSplit("aa"));
System.out.println(maxUniqueSplit("aaaaaaaaaaaaaaaa"));
}
}
Running it prints:
5
2
3
1
1
5
The 5 and 2 at the top match the two examples. Look at the 3 below them: "aaba" gives three pieces, from "aa", "b" and "a", the cut that the shortest-new-piece rule missed. That input also needs used.remove(piece)
The two 1s come from "a" and "aa". A single letter is one piece, and "aa" cannot become "a" and "a", so the whole string stays one piece. The last line is sixteen a's, the longest string allowed. Pieces of a's differ only in length, and six different lengths need at least 1 + 2 + 3 + 4 + 5 + 6 = 21 letters. So 5 is the most, for example with lengths 1, 2, 3, 4 and 6.
Complexity
The cost is the number of cuts the search can follow, times the work for each piece on the way.
- Time: O(n × 2n) in the worst case, where n is the length of the string. The search can follow each of the 2n - 1 ways to cut the string, and each piece costs up to O(n) to copy with
and to hash in the set.substring - Space: O(n). The recursion is at most n calls deep, one call per piece, and the set holds only the pieces of the current path, whose total length is at most n.
The choose, explore and take back pattern is explained in