SDE & MLE Prep

763. Partition Labels

Problem

Split s into as many parts as possible so that each letter appears in at most one part. Return the part sizes in order.

Example: "ababcbacadefegdehijhklij" → [9,7,8]

Record each letter's last index. Extend the current part's end to the max last-index of letters seen; when i == end, cut.

a b a b c b a c a | d e f e g d e | h i j h k l i j
last(a)=8 -> part ends at 8 once all letters inside end by 8

Complexity: O(n).

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        last = {ch: i for i, ch in enumerate(s)}
        res, start, end = [], 0, 0
        for i, ch in enumerate(s):
            end = max(end, last[ch])
            if i == end:
                res.append(end - start + 1)
                start = i + 1
        return res