Partition Labels
1Try it yourself first
Think for 20-30 minutes before you open any hint. Being stuck is where the learning happens.
Only for you, saved in this browser. After you see the approach you will compare it with your idea.2What is being asked
Split a string into as many parts as possible so that each letter appears in at most one part. Return the part sizes.
3Hint ladder
Take one rung at a time. Stop as soon as the idea clicks.
- Hint 1For each letter, where is its last occurrence?
- Hint 2While scanning a part, keep the farthest last-occurrence of any letter seen in it.
4The approach
Have you tried the hints? The approach is built as a path from the obvious way to the clever one.
A bookshelf where each author's books must all go into one box. Look at the first book: its author's last book is at position 5, so the box must reach at least there. Walking through the books of the box you meet other authors whose last book is even farther, so you stretch the box. When you reach the stretched end, nobody inside has books outside: close the box and start the next.
- The obvious way
For each cut point check all letters on both sides: O(n x 26) per cut, O(n²).
- The key insight
Precompute the last position of every letter. Scan the string with the current part's end = farthest last-position seen so far. When the scan reaches that end, close the part (size = end - part start + 1) and begin a new one.
- The algorithm
- Record the last index of each letter.
- Walk the string; end = max(end, last index of this letter).
- Position == end? Record the part size and start a new part.
- Return the sizes.
Watch it run
Examples = "abacbdd"
a's last position is 2, so this part reaches at least 2.
part end = 2
Where people slip
- The part end only grows while scanning; never reset it inside a part.
How close was your idea?
You did not write an idea, and that is fine.
Be honest with yourself. This sets your revision list.
5Code
Try writing it yourself from the steps first. Then compare.
def partition_labels(s):
last = {letter: position for position, letter in enumerate(s)} # last position of each letter
sizes = []
part_start = 0
part_end = 0
for position, letter in enumerate(s):
part_end = max(part_end, last[letter]) # the box must reach this letter's last book
if position == part_end:
sizes.append(part_end - part_start + 1) # nobody inside has books outside: close the box
part_start = position + 1
return sizesNow close this and write it again from memory, in the language you will use in the interview. Reattempt after 1 day, 7 days and about 30 days.
6Still stuck? Watch a video
Seeing someone explain it out loud can make it click. Try the video after you have read the approach above.