Magicsheet logo

Partition Labels

Medium
65.2%
Updated 6/1/2025

Partition Labels

What is this problem about?

The Partition Labels problem asks you to partition a string into as many parts as possible such that each character appears in at most one part. Return the sizes of each part. This coding problem uses a greedy approach based on the last occurrence of each character. The hash table, two pointers, string, and greedy interview pattern is the core.

Why is this asked in interviews?

Microsoft, Meta, Amazon, LinkedIn, Google, and Bloomberg ask this because it tests the greedy insight of extending the current partition to include all characters that have appeared in it. The "last occurrence" precomputation is key.

Algorithmic pattern used

Last occurrence + greedy scan. Precompute last[c] = last index of character c in the string. Scan left to right: maintain end = farthest last occurrence of any character in the current partition. When i == end, the current partition is complete (add size, reset start). Update end = max(end, last[s[i]]) at each step.

Example explanation

s="ababcbacadefegdehijhklij". last: a=8,b=5,c=7,d=14,e=15,f=11,g=13,h=19,i=22,j=23,k=20,l=21.

  • Scan: update end. When i=end=8: partition "ababcbaca", size=9.
  • Continue: end extends to 15 (e). When i=15: partition "defegde", size=7.
  • Continue: end=23. When i=23: size=8. Result: [9,7,8].

Common mistakes candidates make

  • Not precomputing last occurrences.
  • Updating end too late (must update at every step).
  • Off-by-one in partition size: size = end - start + 1.
  • Not resetting start after each partition.

Interview preparation tip

Partition Labels is a beautiful greedy problem. The insight: a partition can end only when all characters within it have been "fully contained" — no character extends beyond the current boundary. The greedy approach naturally finds the minimum number of characters that must be in each group. Practice similar "expand partition to include all occurrences" problems — they all use the same last-occurrence greedy sweep.

Similar Questions