InterviewPrepKit

Home / Coding / Greedy

Partition Labels

medium Original ↗
Solving tips
  • Precompute each letter's last occurrence index, then sweep while extending the current part's end to the running-max last-index of letters seen.
  • Cut a part the moment your scan index equals that running end — every letter inside is fully contained, and this shortest legal cut maximizes the number of parts.
  • Part length is i - start + 1 (inclusive); after a cut set start = i + 1.
  • Target O(n) time and O(1) space (26 letters); don't cut at a letter's first repeat — track the running max last-index instead.

Problem

You are given a string s of lowercase English letters. Partition s into as many contiguous, non-overlapping parts as possible so that each letter appears in at most one part (every occurrence of any given letter must lie inside a single part). The parts, concatenated in order, must reproduce s.

Return a list of the sizes of these parts, in left-to-right order.

Examples

  • s = "ababcbacadefegdehijhklij"[9, 7, 8] — parts "ababcbaca", "defegde", "hijhklij"; e.g. every a is inside the first part, every d/e inside the second.
  • s = "eccbbbbdec"[10]e first appears at index 0 and last at index 8, forcing the whole string into one part.
  • s = "abcdef"[1, 1, 1, 1, 1, 1] — every letter is unique, so each character is its own part.

Constraints

  • 1 <= len(s) <= 500
  • s consists of lowercase English letters only ('a''z').
  • Small input, but the intended solution is a clean O(n) two-pass — no need for anything heavier.

Think about it first

Hint 1 For each letter, what is the earliest a part containing it could possibly end? It cannot end before that letter's last occurrence anywhere in the string.
Hint 2 Precompute the last index at which each of the 26 letters appears. Then walk left to right, tracking how far the current part is forced to extend.
Hint 3 Maintain end = the farthest last-occurrence among all letters seen so far in the current part. When your scan index reaches end, no letter inside the part appears later — cut here and start a new part. Greedily cutting at the first legal spot maximizes the number of parts.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.