Partition Labels

Medium
greedy

You are given a string s. We want to partition the string into as many parts as possible so that each letter appears in at most one part.

Note that the partition is done so that after concatenating all the parts in order, the resultant string should be s.

Return a list of integers representing the size of these parts.

Greedy Insight: For each character, find its last occurrence. As we scan, maintain the farthest "end" we must reach before we can make a partition. When current index equals the end, we've found a partition.

Why Greedy Works: A character must appear entirely within one partition. By tracking the last occurrence of each character in the current partition, we know the minimum endpoint. When we reach it, all characters so far are contained, so we greedily partition.

Example 1

Input: s = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation: The partition is "ababcbaca", "defegde", "hijhklij". Each letter appears in at most one part.

Example 2

Input: s = "eccbbbbdec"
Output: [10]
Explanation: Characters are interleaved such that we cannot split without breaking the constraint. The entire string is one partition.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters.
Show Hints (4)
Hint 1: First, find the last index of each character in the string.
Hint 2: Iterate through the string, tracking the farthest "end" required.
Hint 3: When the current index equals the end, you can make a partition.
Hint 4: The partition size is (current index - start of partition + 1).
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?