← DSA
MEDIUM

Partition Labels

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.

Example

Input s = "ababcbacadefegdehijhklij"
Output [9,7,8]

Key Pointers

Step-by-Step Analysis

  1. Precompute lastIndex, a map from each character to the index of its last occurrence in s.
  2. Initialize start = 0, end = 0, and an empty result list.
  3. For each index i, character c in s: update end = max(end, lastIndex[c]).
  4. If i == end, the partition is complete — append end - start + 1 to the result, then set start = i + 1.
  5. Return the result after the scan finishes.

Complexity

Time: O(n) — Space: O(1) (fixed alphabet size)

Code

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 result

Code Explanation

How the solution above works, piece by piece.

  1. lastIndex records where each letter appears for the last time.
  2. Scan the string, extending end to the furthest last-occurrence of any letter seen in the current part.
  3. When i == end, every letter in the part has no later copies, so the part can close here: record its size.
  4. Start the next part at i + 1.
  5. Two passes, O(n) time, O(26) extra space.

Visual Walkthrough

Running it on s = "ababcbacadefegdehijhklij":

String split into three parts of sizes 9, 7 and 8a0b1a2b3c4b5a6c7a8d9e10f11e12g13d14e15h16i17j18h19k20l21i22j23size 9size 7size 8a part ends where the furthest last-occurrence of its letters is reached
Every letter must stay inside one part, so a part can only end once it has passed the last occurrence of every letter it contains. Growing end to cover those last occurrences gives parts of 9, 7 and 8.
part 1part 2part 3

Video Explanation

NeetCode — Partition Labels, LeetCode 763