#763

Partition Labels

Medium Last occurrence

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Split a string into as many parts as possible so each letter appears in at most one part. Return the part sizes.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: cut the string into as many parts as possible with no letter in two parts.

Why this works: a part must reach the last occurrence of every letter inside it; cut when the scan reaches that point.

Example: "ababcbacadefegdehijhklij"

first part ends at last 'a' (index 8) → 9then "defegde" → 7, then "hijhklij" → 8

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Closing a part at the last index of only its first letter.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(26).
Topic: Greedy
🎬 Episodes 69–73: video coming soon