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
- First pass: record last index of each character
- Second pass: track partition end as max of last indices seen
- When current index equals partition end, we found a partition
- Start new partition from next index
Related Data Structures & Algorithms exercises
- Practice Activity Selection (Interval Scheduling) in Java
- Practice Gas Station in Java
- Practice Task Scheduler in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler