Algorithms · Visualized
Partition Labels
Greedy
Make the locally optimal choice at each step, hoping it leads to a globally optimal solution.
Splits a string into as many parts as possible so that each letter appears in only one part. Time: O(n) average, O(n) worst; space: O(1) — fixed-size alphabet map.
Big-O: Works when the problem has optimal substructure + greedy-choice property — e.g. intervals, Huffman, fractional knapsack.
Partition Labels
GreedySplits a string into as many parts as possible so that each letter appears in only one part. The greedy approach: for each character, know the last index where it appears anywhere in the string; extend the current partition's boundary to cover the last occurrence of every character seen so far, and cut a new partition once you reach that boundary.
How Partition Labels Works
- First pass: record the last occurrence index of every character in the string.
- Second pass: track 'start' (beginning of the current partition) and 'end' (the furthest last-occurrence seen so far in this partition), both starting appropriately.
- For each character in the string, update 'end' to be the maximum of its current value and that character's last occurrence index.
- If the current index reaches 'end', the partition is complete — record its length (end - start + 1), then set 'start' to the next index.
- Continue through the whole string; the collected partition lengths are the answer.
Partition Labels Worked Example
Input: ababcbacadefegdehijhklij
Last occurrence: a=8,b=5,c=7,d=14,e=15,f=11,g=13,h=19,i=22,j=23,k=20,l=21. Start scanning: 'a'(end=8),'b'(end=8),'a'(end=8)...reach index8, close partition length9 ('ababcbaca'). Next partition starts at 9: 'd'(end=14),'e'(end=15)... reach index15, close partition length7 ('defegde'). Remaining: 'hijhklij' forms the last partition, length8. Result: [9,7,8].
def partition_labels(s):
last = {c: i for i, c in enumerate(s)}
parts = []
start = end = 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end:
parts.append(end - start + 1)
start = i + 1
return partsBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Partition Labels Time & Space Complexity
When to Use Partition Labels
- Text/data chunking where each 'key' must be fully contained in one segment — useful for log partitioning or data sharding by key locality.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.