Partition Labels

35 min · partitionLabels()

Imagine filing a message into folders with one strict rule: a letter may belong to only one folder. Your job is to create as many folders as the message allows.

Given a lowercase string s, split it into as many non-empty contiguous parts, blocks made from neighboring characters, as possible so that every distinct letter appears in at most one part. Return the sizes of those parts from left to right.

You must use every character exactly once and preserve the original order. A letter may appear many times inside its one part; it just can't cross a boundary.

Constraints

  • 1 <= s.length <= 10_000
  • s contains only lowercase English letters a through z.

Hints

Draw each letter's reach

Record the first and last position of every letter. A part containing that letter must cover its entire span.

A boundary can move while you scan

Start a part and set its tentative end to the current letter's last occurrence. Every letter you meet before that end may push the end farther right.

Cut at the first safe position

When your index reaches the furthest last occurrence seen inside the current part, none of its letters appears later. Cut there immediately to leave the most room for future parts.

Follow-up

Could you return the actual substrings instead of their sizes without changing the asymptotic complexity?

Visible cases

Examples

Example 1

ready
Input
s = "ababcbacadefegdehijhklij"
Expected
[
  9,
  7,
  8
]
Why
each cut waits until every letter in its part has finished

Example 2

ready
Input
s = "eccbbbbdec"
Expected
[
  10
]
Why
the repeated e and c spans tie the whole string together

Example 3

ready
Input
s = "abaccbdeffed"
Expected
[
  6,
  6
]
Why
the letters form two independent six-character regions

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite