Partition Labels solution explained

Partition Labels is solved with a last-occurrence table and one greedy scan. Record where each letter appears for the last time, then walk the string while stretching a boundary to the furthest last occurrence seen in the current piece; when your index reaches that boundary, cut. This gives the maximum number of pieces in O(n) time.

By Published 7 min read

The problem, reworded

You are given a string of lowercase letters. Cut it into consecutive pieces, keeping the original order, such that any given letter shows up in at most one piece. Among all valid ways to cut, use the one with the most pieces, and return a list of the piece lengths from left to right.

Strings made up for this page, with answers from the code below
StringPiece lengthsPieces
baccbdeefggf[5, 1, 2, 4]baccb | d | ee | fggf
pqpxyzyx[3, 5]pqp | xyzyx
abcdef[1, 1, 1, 1, 1, 1]Every letter is unique, so every letter is a piece
racecar[7]The r at both ends forces one piece
mississippi[1, 10]m stands alone; i, s and p are tangled together
Strings made up for this page, with answers from the code below. Scroll sideways on a small screen.

Clarify the alphabet (a fixed set of 26 letters lets you use an array instead of a map), whether the string can be empty, and whether the interviewer wants the lengths or the pieces themselves. Returning lengths is the common form; returning pieces is a one-line change.

Why it is asked

Partition Labels is a gentle test of greedy reasoning on strings. It rewards a candidate who stops to ask what forces a piece to be longer, rather than one who starts cutting and patching. It also connects neatly to interval problems, and interviewers like to see a candidate notice that link without being prompted.

First try: check every cut point

Walk the string and consider cutting after each position. A cut is safe if no letter in the current piece appears again to the right of the cut. Check it by comparing the set of letters in the current piece with the set of letters still ahead. If they share nothing, cut and start a new piece. Building those sets at every position makes it O(n²), which is slow on long text but useful as a test reference.

def chunk_sizes_slow(text):
    sizes = []
    start = 0
    for cut in range(len(text)):
        left = set(text[start:cut + 1])
        right = set(text[cut + 1:])
        if not (left & right):
            sizes.append(cut + 1 - start)
            start = cut + 1
    return sizes
Set comparison at every position: O(n²).

The key fact: a piece must reach every letter's last copy

Suppose the current piece contains the letter c. Then every copy of c must be in this piece, so the piece cannot end before c's last position in the whole string. Apply that to every letter in the piece, and the earliest place the piece can end is the largest last position among its letters. That boundary can grow as you scan, because each new letter may bring a later last position with it.

When the scan index finally equals the boundary, every letter seen in this piece has had its last appearance, so cutting here is legal. Cutting as early as legally possible never hurts, because it leaves the rest of the string as free as it can be for more cuts. That is why the greedy gives the maximum count.

def chunk_sizes(text):
    last = {ch: i for i, ch in enumerate(text)}  # final position of each letter
    sizes = []
    start = 0
    reach = 0
    for i, ch in enumerate(text):
        reach = max(reach, last[ch])
        if i == reach:  # nothing seen so far appears after i
            sizes.append(i - start + 1)
            start = i + 1
    return sizes
Python: one pass to record last positions, one pass to cut. O(n) time.
function chunkSizes(text) {
  const last = new Map();
  for (let i = 0; i < text.length; i++) last.set(text[i], i);
  const sizes = [];
  let start = 0;
  let reach = 0;
  for (let i = 0; i < text.length; i++) {
    reach = Math.max(reach, last.get(text[i]));
    if (i === reach) {
      sizes.push(i - start + 1);
      start = i + 1;
    }
  }
  return sizes;
}
JavaScript: the same two passes with a Map.

Trace on baccbdeefggf

Last positions: b 4, a 1, c 3, d 5, e 7, f 11, g 10
IndexLetterBoundary after reading itCut?
0b4No
1 to 3a, c, c4No, nothing reaches past 4
4b4Yes, piece of length 5
5d5Yes, piece of length 1
6, 7e, e7Yes at 7, piece of length 2
8 to 11f, g, g, f11Yes at 11, piece of length 4
Last positions: b 4, a 1, c 3, d 5, e 7, f 11, g 10. Scroll sideways on a small screen.

The interval view

Give each distinct letter a range from its first index to its last index. In the example, b covers 0 to 4, c covers 2 to 3, f covers 8 to 11 and g covers 9 to 10. Two letters must share a piece exactly when their ranges overlap, directly or through a chain. So the pieces are the merged ranges, and their lengths are the answer. You could sort the ranges and merge them as in Merge Intervals. The scan above does the same merge for free, because the ranges are discovered in order of their start positions.

Complexity

n characters, k distinct letters
ApproachTimeExtra space
Compare letter sets at every cutO(n²)O(n) for the sets
Last positions plus greedy scanO(n)O(k), at most 26 entries for lowercase letters
Build ranges, sort, mergeO(n + k log k)O(k)
n characters, k distinct letters. Scroll sideways on a small screen.

Edge cases

  • An empty string returns an empty list.
  • A single letter, or one letter repeated, is one piece.
  • A string whose first and last letters match is always a single piece, as with racecar.
  • All distinct letters give a piece per letter.
  • Letters that appear once in the middle of a long piece do not create a cut, since the boundary already reaches past them.

Frequent errors

  • Using the first occurrence instead of the last when building the table.
  • Cutting when a letter's last position is reached, instead of when the boundary is. The boundary covers all letters in the piece, not just the current one.
  • Forgetting to move the start of the next piece to i + 1, which makes every later length too long.
  • Returning the cut indexes when the question asked for lengths, or the reverse.

Follow-up questions

  • Return the pieces instead of the lengths. Slice from the piece start to i + 1 at each cut.
  • The string arrives as a stream. You cannot know a letter's last position in advance, so you cannot cut safely until the stream ends. Say that clearly rather than forcing a streaming answer.
  • Each piece must hold at least m letters. The greedy no longer maximizes the count by itself; you may need to merge short pieces with a neighbor, and a table over cut positions is the safe fallback.
  • Group lines in a log so each user ID appears in one block. It is the same problem with user IDs as the letters.

In your own words

Fictional example

A quick spoken explanation
Candidate
Every copy of a letter has to stay in one piece, so a piece can't end before the last copy of any letter in it.
Candidate
I'll store each letter's last index, then scan and keep the furthest last index among the letters in my current piece. When my index reaches that boundary, I cut.
Candidate
Cutting at the earliest legal point leaves the most room for more cuts, so this maximizes the number of pieces. It's O(n) time with a table of at most 26 entries.

Merge Intervals is the explicit version of the interval view above. Jump Game II uses the same move of pushing a boundary forward and acting when the scan meets it. Non-overlapping Intervals is a greedy interval problem where the sort key decides correctness. See the coding problems hub for the full list.

Natively as a study aid

If you practice on a Mac or a Windows PC, Natively can read this prompt from a screenshot and help you check whether your boundary logic covers every letter in the piece. Your mock interview is transcribed and saved along with notes, which makes it easy to spot where your explanation of the greedy choice got vague. Learn more on the AI interview assistant page.

Questions people ask

How do you solve Partition Labels?

Record the last index of every letter. Scan the string keeping a boundary equal to the largest last index among the letters in the current piece, and cut when the scan index reaches that boundary.

Why does the Partition Labels greedy give the most pieces?

A piece can never end before the last copy of any letter in it, and cutting at the earliest legal point leaves the rest of the string as free as possible for more cuts.

What is the complexity of Partition Labels?

O(n) time for two passes over the string, and O(k) extra space for the last-position table, where k is the number of distinct letters.

How is Partition Labels related to Merge Intervals?

Treat each letter as the range from its first to its last position. Overlapping ranges must share a piece, so the pieces are the merged ranges.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP