Partition Labels

MediumGreedy
Asked byAmazonGoogle

Problem

Given a string, partition it into as many parts as possible so that each letter appears in at most one part, and return the lengths of those parts.

Examples

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

Constraints

  • 1 <= s.length <= 500

Solve it in the editor. Sign in free to run your Python or JavaScript against test cases, get a verdict, and track your attempts.

Solve on FeatCode →

How to approach it: the Greedy pattern

Make the choice that looks best right now, without reconsidering it later, and trust that a sequence of locally optimal choices adds up to a globally optimal answer. It only works when the problem actually has that property.

Look for this pattern when

  • Sorting the input by some key, then making one pass with simple local decisions, intuitively seems to produce the best answer.
  • The problem involves intervals, scheduling, or resource allocation where "always take the best available option" tends to work.

Read the full Greedy guide →

Video walkthroughs

Original problem on LeetCode ↗

More Greedy problems