Partition Labels

Cut a string into as many parts as possible so that no letter appears in two parts.

Given a string s of lowercase letters, split it into as many parts as possible so that each letter appears in at most one part. Joining the parts in order must give back s. Return the sizes of the parts, in order.

Example 1
Input: s = "ababcbacadefegdehijhklij"
Output: [9, 7, 8]
Explanation: the parts are "ababcbaca", "defegde" and "hijhklij".
Example 2
Input: s = "eccbbbbdec"
Output: [10]
Explanation: the string starts and ends with e, so it cannot be split.
Solution

The Idea

Picture a ribbon printed with the letters of s, and a pair of scissors. You want to cut the ribbon into as many parts as you can, but each letter may show up on one part only. In Example 1 the ribbon has 24 letters, and the answer cuts it into ababcbaca, defegde and hijhklij, parts of 9, 7 and 8 letters.

Why not cut right after the first two letters, ab? Because more a's and b's come later, and they would land on another part. Number the positions from 0, as Java does; each number is an index. The first part starts with an a, so it must run at least to the last a in the string, at index 8.

Is reaching index 8 enough? Every letter picked up on the way brings its own last copy, which could lie further on. Here the last b is at index 5 and the last c at index 7, both before 8, so nothing pushes the part further. At index 8, every letter in the part has used up all its copies, and a cut is allowed. So the real question is: while walking along the string, how far must the current part reach?

Look at the picture below. Under the string, each letter has a bar from its first copy to its last copy.

The string ababcbacadefegdehijhklij with indexes 0 to 23. Under it, a bar for each letter runs from its first copy to its last copy. The bars for a, b and c end by index 8, those for d, e, f and g by index 15, and the rest by 23, so the cuts go after 8 and after 15.

The orange bar, a: 0 to 8, covers the bars for b and c, so the first cut goes right after index 8. In part 2, the bar d: 9 to 14 is stretched by e: 10 to 15, and the second cut goes after 15. In part 3, the bars for h, i and j overlap until j ends at index 23.

So the end of the current part is the farthest last index among the letters it holds so far, and the part can close when the walk reaches that end. Cutting there never leaves fewer parts in the end. No split can cut earlier, because some letter inside would still have a copy after the cut, and everything after the cut is free to be split on its own.

Cutting the ribbon at the first place a cut is allowed, without trying later places first, is called a greedy choice: it takes what looks best right now and never comes back to it.

Solution Approach

Turning that idea into code means settling three things: how to find each letter's last index quickly, how to track the end of the current part, and when to cut.

Each letter's last index

Where does a letter appear for the last time? Calling s.lastIndexOf(c) whenever the walk meets a letter works, but each call can scan up to the whole string. For a string of n letters, that is up to n steps for each of the n letters, about n² in all.

Instead, one pass before the walk fills an array last with 26 cells, one for each letter from a to z. Subtracting 'a' from a letter gives its cell: 0 for a, 1 for b, up to 25 for z. The pass writes each index into its letter's cell, so a later copy overwrites an earlier one. When the pass ends, the cell for a holds 8, the cell for b holds 5, and the cell for c holds 7.

The end of the current part

How far must the current part reach? A variable end keeps track. At each index, the letter there needs the part to reach its last index, so end becomes the larger of end and that last index. Taking the larger value means end never moves back, and it always holds the farthest last index of any letter already in the part.

When to cut

When is the part complete? When the walk's index equals end. Every letter seen since the part began has its last copy at or before this index, so none of them shows up later. A variable start remembers where the part began, so its size is end - start + 1, and the next part begins at the next index.

In Example 2, eccbbbbdec, the e at index 0 has its last copy at index 9. So end jumps to 9 at the very first step, and the walk only reaches it at the last letter: one part of size 10.

Java Solution

The method partitionLabels works in these steps:

  1. First, fill the array last with a loop over s: for each index i, set last[s.charAt(i) - 'a'] to i.
  2. Create the list sizes for the answer, and two variables set to 0: start, where the current part begins, and end, how far it must reach.
  3. Walk the string again with a second loop over i. At each index, set end to Math.max(end, last[s.charAt(i) - 'a']).
  4. If i equals end, add end - start + 1 to sizes and set start to i + 1.
  5. After the second loop, return sizes.

The main method runs both examples, a single letter, three different letters, a string whose middle letters sit between its two a's, and a string where each letter's copies sit together.

Java
import java.util.ArrayList;
import java.util.List;

public class PartitionLabels {

    public static List<Integer> partitionLabels(String s) {
        int[] last = new int[26];
        for (int i = 0; i < s.length(); i++) {
            last[s.charAt(i) - 'a'] = i;              // a later copy overwrites an earlier one
        }
        List<Integer> sizes = new ArrayList<>();
        int start = 0;
        int end = 0;                                  // the current part must reach at least here
        for (int i = 0; i < s.length(); i++) {
            end = Math.max(end, last[s.charAt(i) - 'a']);
            if (i == end) {                           // every letter seen so far ends in this part
                sizes.add(end - start + 1);
                start = i + 1;
            }
        }
        return sizes;
    }

    public static void main(String[] args) {
        System.out.println(partitionLabels("ababcbacadefegdehijhklij"));
        System.out.println(partitionLabels("eccbbbbdec"));
        System.out.println(partitionLabels("a"));
        System.out.println(partitionLabels("abc"));
        System.out.println(partitionLabels("abcba"));
        System.out.println(partitionLabels("aabbccdd"));
    }
}

Running it prints:

Output
[9, 7, 8]
[10]
[1]
[1, 1, 1]
[5]
[2, 2, 2, 2]

[9, 7, 8] and [10] match the two examples, and the single letter "a" gives [1]. For "abc", each letter's last index is its own index, so i equals end at every step and the line reads [1, 1, 1]. For "abcba", the a at index 0 sets end to 4, and the b's and the c inside never push it past 4, so the line is [5]. The last line, [2, 2, 2, 2], is one part per pair of equal letters.

Why Math.max, and not simply end = last[s.charAt(i) - 'a']? Without it, a letter whose last copy comes early can pull end back. In Example 1, the b at index 5 is the last b, so end would become 5. The walk would cut there, putting the a's at 6 and 8 in a different part from the a's at 0 and 2. Run on Example 1, that version returns 12 parts: [6, 2, 1, 3, 2, 1, 1, 4, 1, 1, 1, 1].

Complexity

The work is two walks over the string, with an array of 26 cells on the side.

  • Time: O(n), because the first loop visits each of the n letters of s once to fill last, and the second visits each again with one lookup and one comparison.
  • Space: O(1) besides the output, because last has 26 cells however long s is, and sizes has at most 26 entries since no letter appears in two parts.

Each bar in the picture is an interval, a stretch from a first index to a last index, and each part is a group of overlapping bars. Joining overlapping intervals is the whole task in Merge Intervals.