Optimal Partition of String
Cut a string into the fewest pieces in which no letter appears twice.
Given a non-empty string s
Example 1
Output: 4
Explanation: for example "ab", "ac", "ab", "a".
Example 2
Output: 6
Explanation: every "s" must be on its own.
The Idea
Think of a word written on a strip of paper. Each piece you cut off is one substring. You want as few pieces as possible, but no piece may show the same letter twice. Example 2 is easy: "ssssss" has six s's, each piece can hold only one, so it takes six pieces.
Example 1, "abacaba", leaves room for choice. Cutting after every letter gives seven pieces, which is allowed but wasteful. The first piece could be "a" alone, or "ab", but not "aba", because that shows a twice. So where should each cut go?
A natural plan is to keep each piece going for as long as it can. Read the letters from the left and add each one to the current piece. Only when the next letter is already in the piece does the piece end, and that letter starts a new one. Look at the picture below.
Piece 1 takes a and b. The next letter, the first orange a, is already in piece 1, so piece 2 starts with it and takes c as well. The next a is already in piece 2, so it starts piece 3, which takes b. The last a starts piece 4. That makes 4 pieces, the answer to Example 1.
Taking the move that looks best right now, and never going back on it, is called a greedy approach. But could a shorter piece now leave room for fewer pieces later? Compare the greedy pieces with any other valid way to cut the strip, piece by piece.
The greedy first piece ends only at a repeat, so it reaches at least as far as the other first piece. The greedy second piece therefore starts at the same place as the other second piece, or later.
Now take the letters from where the greedy second piece starts to where the other second piece ends. They all lie inside the other second piece, which has no repeated letter, so they have none either. The greedy second piece can hold all of them, so it again reaches at least as far.
The same holds for the third piece, the fourth, and every piece after. Greedy is never behind the other way of cutting, so it never needs more pieces. Cutting as late as possible is always a best answer.
Solution Approach
Turning that idea into code means settling three things: why trying every set of cuts is too slow, how to remember the letters of the current piece, and how to count the pieces.
Trying every set of cuts
Why not try every way to cut the string and keep the best one? Between two neighbouring letters there either is a cut or there is not. "abacaba" has six such gaps, so 26 = 64 ways to cut it. A string of 40 letters has 239 ways, more than 500 billion. The greedy plan reads each letter once instead.
Remembering the letters of the current piece
For every letter, the code must answer one question: is this letter already in the current piece? A HashSet<Character>containsaddclear
Since the string holds only the 26 lowercase letters, a single intintint
For a letter chch - 'a'1 << (ch - 'a')usedbit
is true exactly when the letter's bit is already on, so the letter is in the piece.(used & bit) != 0 switches the letter's bit on, adding it to the piece.used |= bit switches every bit off, which empties the piece.used = 0
Counting the pieces
When does the count go up? The first letter always opens a piece, so the count starts at 1. After that, it grows by one at each repeat. The repeating letter is not dropped: it is the first letter of the new piece, so it must be added to used
Java Solution
The method partitionString
- First, set
to 1, for the piece the first letter opens, andpieces to 0, an empty bitmask for the letters of the current piece.used - Go through the string with one loop over the index
, and turn each letteri into itss.charAt(i) withbit .1 << (s.charAt(i) - 'a') - If
is not 0, the letter is already in the current piece: add one toused & bit and setpieces to 0 to start a new, empty piece.used - In both cases, switch the letter's bit on with
, so the letter joins the current piece, whether old or new.used |= bit - After the loop, return
.pieces
The main
public class OptimalPartitionOfString {
public static int partitionString(String s) {
int pieces = 1; // the first letter opens the first piece
int used = 0; // bit c is on if letter c is in the current piece
for (int i = 0; i < s.length(); i++) {
int bit = 1 << (s.charAt(i) - 'a');
if ((used & bit) != 0) {
pieces++; // the letter repeats: start a new piece
used = 0;
}
used |= bit; // the letter joins the current piece
}
return pieces;
}
public static void main(String[] args) {
System.out.println(partitionString("abacaba"));
System.out.println(partitionString("ssssss"));
System.out.println(partitionString("a"));
System.out.println(partitionString("abcdefghijklmnopqrstuvwxyz"));
System.out.println(partitionString("hdklqkcssgxlvehva"));
System.out.println(partitionString("aaa"));
}
}
Running it prints:
4
6
1
1
4
3
The 4 and 6 at the top match Examples 1 and 2. Look at the fourth line: all 26 letters fit into one piece, since none of them repeats. The fifth line comes from "hdklqkcssgxlvehva", which the loop cuts into "hdklq", "kcs", "sgxlveh" and "va", 4 pieces.
The last line, 3 for "aaa", depends on step 4. Suppose used |= bitelse
The original implementation,
Complexity
The method reads the string once and remembers only two numbers while it does.
- Time: O(n), where n is the number of letters in
. The loop visits each letter once, and each visit is one bit test, at most one reset and one bit switched on.s - Space: O(1). Whatever the length of
, the state is the counts and the bitmaskpieces , andused reads the letters in place, without copying the string.charAt
When the pieces must be different strings rather than have different letters, greedy no longer works: see