Data Structures & Algorithms Greedy Algorithms
💡
Exercise 141

Partition Labels 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Partition a string so each letter appears in at most one part. Return the sizes of the parts. Maximize the number of parts.

Greedy: find the last occurrence of each character. Scan left to right, extending the current partition's end to include all last occurrences.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Find partition sizes for 'ababcbacadefegdehijhklij'.
Build last_index map. Track partition end. When i == end, partition is complete. Record size and start new partition.
🧪 Test Cases
Input
partitionLabels('ababcbacadefegdehijhklij')
Expected
[9, 7, 8]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.