Partition Labels - Problem
You are given a string s and need to partition it into as many parts as possible while ensuring each letter appears in at most one part.
Think of this as cutting a string into segments where no character appears in multiple segments. For example, with the string "ababcbacadefegdehijhklij", you need to find the optimal cutting points.
Goal: Return a list of integers representing the size of each part after partitioning.
Example: "ababcbaca" can be partitioned as ["ababcbaca"] (size 9) because 'a', 'b', and 'c' are all intertwined throughout the string. But "ababccdd" could be partitioned as ["abab", "cc", "dd"] (sizes [4, 2, 2]).
Input & Output
example_1.py โ Basic Case
$
Input:
s = "ababcbacadefegdehijhklij"
โบ
Output:
[9,7,8]
๐ก Note:
The partitions are "ababcbaca", "defegde", "hijhklij". Each letter appears in only one partition. The first partition must include all positions of 'a', 'b', 'c' which forces it to be "ababcbaca" (length 9).
example_2.py โ Simple Case
$
Input:
s = "eccbbbbdec"
โบ
Output:
[10]
๐ก Note:
Since 'e' appears at positions 0 and 9, and 'c' appears at positions 1 and 8, the entire string must be one partition. No valid splits are possible without having characters appear in multiple partitions.
example_3.py โ Single Character
$
Input:
s = "a"
โบ
Output:
[1]
๐ก Note:
Edge case with single character - the entire string is one partition of length 1.
Constraints
- 1 โค s.length โค 500
- s consists of lowercase English letters only
- Each character appears at least once
Visualization
Tap to expand
Understanding the Visualization
1
Survey Properties
Walk through the street and note the last property owned by each family
2
Plan Boundaries
For each neighborhood, extend the boundary until it includes the last property of every family encountered
3
Finalize Neighborhoods
Close a neighborhood boundary only when all families in it are fully contained
Key Takeaway
๐ฏ Key Insight: The optimal partition boundary can only occur at positions where we've encountered the last occurrence of every character seen in the current partition.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code