v9.1.1
Menu

Partition Labels

mediumPROGreedy & IntervalsAmazon DSA

Given a string s, partition it into as many parts as possible so that each letter appears in at most one part. Return the sizes of these parts as a list of integers, in left-to-right order.

The tests print the returned sizes as space-separated integers.

Example

Input
ababcbacadefegdehijhklij
Output
9 7 8
Reasoning
  • The input s has 24 lowercase letters at positions 00 to 2323. The output lists part lengths from left to right.
  • Every copy of a letter must land in the same part. The first a is at position 00 and the last at position 88, so the first part covers at least positions 00 to 88. Inside that span, b and c last appear at 55 and 77, so nothing crosses the boundary and the first part is ababcbaca, length 99.
  • The second part starts with d (last copy at 1414), and it contains e, whose last copy is at 1515. Nothing in positions 99 to 1515 reaches further, giving defegde, length 77.
  • The final part hijhklij covers positions 1616 to 2323, length 88, because j appears again at the very end.
  • Notice that 9+7+8=249 + 7 + 8 = 24. The parts tile the whole string, and each cut is made as early as the letters allow, which is what makes the number of parts as large as possible.

Constraints

  • 1 <= len(s) <= 500
  • s consists of lowercase English letters

Learn this in

More from Amazon DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.