Partition Labels in Java: Explanation & Practice

Partition string so each letter appears in at most one part

Problem summary

Given a string, partition it into as many parts as possible so that each letter appears in at most one part. Return the size of each part.

Starter code

public class Main {
    public static void main(String[] args) {
        String s = "ababcbacadefegdehijhklij";
        
        // For each char, track its last occurrence
        // Extend partition to include last occurrence of all chars in it
        // Print: 9 7 8
    }
}

Expected output and test cases

  • ababcbacadefegdehijhklij
    9 7 8
  • eccbbbbdec → one partition
    10
  • abc → each letter once
    1 1 1

Hints

  1. First pass: record last index of each character
  2. Second pass: track partition end as max of last indices seen
  3. When current index equals partition end, we found a partition
  4. Start new partition from next index

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler