PracticeNeetCode ↗LeetCode ↗
Given a string s, split it into as many parts as possible such that each letter appears in at most one part. Return the list of part lengths.
lastIndex, a map from each character to the index of its last occurrence in s.start = 0, end = 0, and an empty result list.i, character c in s: update end = max(end, lastIndex[c]).i == end, the partition is complete — append end - start + 1 to the result, then set start = i + 1.Time: O(n) — Space: O(1) (fixed alphabet size)
def partitionLabels(s: str) -> list[int]:
lastIndex = {c: i for i, c in enumerate(s)}
result = []
start = end = 0
for i, c in enumerate(s):
end = max(end, lastIndex[c])
if i == end:
result.append(end - start + 1)
start = i + 1
return resultHow the solution above works, piece by piece.
lastIndex records where each letter appears for the last time.end to the furthest last-occurrence of any letter seen in the current part.i == end, every letter in the part has no later copies, so the part can close here: record its size.i + 1.Running it on s = "ababcbacadefegdehijhklij":
end to cover those last occurrences gives parts of 9, 7 and 8.