InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Greedy

Partition Labels

medium Original ↗ 00:00

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').
  • The input is small, but the intended solution is an O(n) two-pass scan.

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug