Optimal Partition of String

Cut a string into the fewest pieces in which no letter appears twice.

Given a non-empty string s of lowercase English letters, cut it into substrings (runs of neighbouring letters) so that no letter appears twice within the same substring. Every letter belongs to exactly one substring. Return the smallest number of substrings this can be done with.

Example 1
Input: s = "abacaba"
Output: 4
Explanation: for example "ab", "ac", "ab", "a".
Example 2
Input: s = "ssssss"
Output: 6
Explanation: every "s" must be on its own.
Solution

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.

The string abacaba read from left to right and cut into four pieces: piece 1 is ab, piece 2 is ac, piece 3 is ab and piece 4 is a. Each new piece starts at an a that is already in the current piece.

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> can answer it, with contains to check, add to add and clear to start a new piece.

Since the string holds only the 26 lowercase letters, a single int can do the same job with less work. An int is made of 32 bits, each 0 or 1. Give each letter its own bit: a gets bit 0, b gets bit 1, and so on up to z, which gets bit 25. A bit that is 1 means "this letter is in the piece". An int used as a row of yes-or-no flags like this is called a bitmask.

For a letter ch, ch - 'a' is its place in the alphabet, 0 for a and 25 for z. Then 1 << (ch - 'a') shifts a single 1 to that place, giving a number with only the letter's bit on. Call the bitmask used and that number bit:

  • (used & bit) != 0 is true exactly when the letter's bit is already on, so the letter is in the piece.
  • used |= bit switches the letter's bit on, adding it to the piece.
  • used = 0 switches every bit off, which empties the piece.

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 right after the reset.

Java Solution

The method partitionString works in these steps:

  1. First, set pieces to 1, for the piece the first letter opens, and used to 0, an empty bitmask for the letters of the current piece.
  2. Go through the string with one loop over the index i, and turn each letter s.charAt(i) into its bit with 1 << (s.charAt(i) - 'a').
  3. If used & bit is not 0, the letter is already in the current piece: add one to pieces and set used to 0 to start a new, empty piece.
  4. In both cases, switch the letter's bit on with used |= bit, so the letter joins the current piece, whether old or new.
  5. After the loop, return pieces.

The main method runs both examples, a single letter, all 26 letters in a row, a longer mixed string, and "aaa".

Java
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:

Output
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 |= bit sat in an else branch, running only when there is no repeat. Then the a that opens a new piece is never recorded. That version returns 2 for "aaa", 3 for "abacaba" and 4 for "ssssss", all too small.

The original implementation, OptimalPartitionOfString.java, is on GitHub.

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 s. The loop visits each letter once, and each visit is one bit test, at most one reset and one bit switched on.
  • Space: O(1). Whatever the length of s, the state is the count pieces and the bitmask used, and charAt reads the letters in place, without copying the string.

When the pieces must be different strings rather than have different letters, greedy no longer works: see Break a String Into Maximum Number of Unique Substrings.