Algorithm Day81 - Partition Labels
π§© Problem Description
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
π¬ Example
1 | Input: S = "ababcbacadefegdehijhklij" |
π‘ Intuition
We want to cut the string into maximum number of parts such that no character appears in more than one part.
Key idea: for each character, precompute its last occurrence index. Then scan the string and maintain a running end which is the farthest last occurrence of characters seen so far. When the current index reaches end, we can close a partition (from previous cut to end) and start a new one.
This is a greedy strategy: always close a partition as soon as every character inside it cannot appear later.
π’ Java Code (Greedy)
1 | import java.util.*; |
β± Complexity Analysis
- Time: O(n) β one pass to compute last positions and one pass to partition.
- Space: O(1) (excluding output) β fixed-size array of 26 for lowercase letters.
βοΈ Summary
- Precompute each characterβs last occurrence.
- Scan and extend the current partitionβs end to cover all last occurrences of letters seen.
- When current index equals the partition end, emit partition size and start a new one.
Related problems
lc-763variations with different alphabets or constraints