MediumHash TableTwo PointersStringGreedy

1 approach, code in every language

Problem description

You are given a string made up of lowercase English letters. Your job is to break it into the largest possible number of contiguous pieces so that every letter ends up in exactly one piece. In other words, no letter may appear in two different pieces.

When the pieces are concatenated back together in order they must reproduce the original string. Return a list containing the length of each piece, in left-to-right order.

Example 1

Input: s = "ababcbacadefegdehijhklij"

Output: [9,7,8]

The split is "ababcbaca", "defegde", "hijhklij". Every distinct letter is confined to a single piece, and using fewer cuts would force some letter to straddle a boundary.

Example 2

Input: s = "eccbbbbdec"

Output: [10]

Both 'e' and 'c' reappear near the end, so the last occurrence of the earliest letters reaches the end of the string. The whole string must stay as one piece.

Constraints

  • 1 <= s.length <= 500
  • s consists of lowercase English letters only.

After the pattern

Now solve one you haven't seen.

Duty Roster Blocks is our own problem on the technique behind Partition Labels: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free