AceYourInterviews
Checking sign-in…

144. Partition Labels

IntermediateEarliest safe cuts forced by last-occurrence interval closure

Split the string into as many nonempty contiguous parts as possible while ensuring that every distinct letter appears in at most one part. Preserve the original order of all characters.

Every occurrence of one letter must remain inside a single part. Return the part lengths rather than reordered letters or a single maximum-length part.

Example 1

Input

text="ababcbacadefegdehijhklij"

Output

[9,7,8]

Explanation: The first nine characters form one forced closure, then seven, then eight.

Example 2

Input

text="eccbbbbdec"

Output

[10]

Explanation: The outer e/c occurrences force the entire string into one part.

Example 3

Input

text="abc"

Output

[1,1,1]

Explanation: Every cut is safe when no character repeats.

Constraints

  • 0 <= text.length <= 105
  • text contains only lowercase English letters.
Hints
Hint 1

What forbids a cut between two occurrences of the same character?

Hint 2

As the current part grows, which encountered character forces the farthest endpoint?

Hint 3

Cut when the scan reaches the maximum last occurrence of everything in the current part.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

A later character extends the current closure

"abacbdde"
[5,2,1]