15% off all plans & roadmaps Use code

See plans

Partition Labels

Updated

TL;DR: Split a string into as many pieces as possible so no letter appears in two pieces. Record each letter's last index, sweep left to right, and cut whenever the index reaches the farthest last index seen in the current piece.

Problem

You are given a string s. Split it into one or more contiguous, nonempty parts so that joining the parts in order gives back s. Every letter must live in exactly one part: if a letter occurs several times, all of its occurrences have to sit inside the same part.

Among all valid splits, pick the one with the most parts. That split is unique. Return an array with the sizes of its parts, from left to right.

Example 1

Input: s = "abac"
Output: [3,1]
Explanation: The first part is aba and the second is c. Cutting earlier would put the two a characters in different parts.

Example 2

Input: s = "qrrqst"
Output: [4,1,1]
Explanation: The first part must be qrrq, because both q characters and both r characters belong together. Each remaining character can be its own part.

Example 3

Input: s = "mnop"
Output: [1,1,1,1]
Explanation: Every letter appears once, so each one can be isolated in its own part.

Constraints

  • 1 <= s.length <= 10^5
  • s contains only lowercase English letters.
  • Every character occurrence belongs to exactly one part, and the returned sizes are positive integers that add up to s.length.

Constraints that matter

  • n up to 10^5 rules out any approach that is cubic, and a quadratic scan of 10^10 operations is too slow in the worst case. Aim for one or two linear passes.
  • Only lowercase letters means a fixed array of 26 slots replaces a hash map. Extra space for the lookup tables is O(1).
  • The answer is unique, so you never have to compare candidate partitions. A single greedy rule that cuts as early as possible is enough.
  • n >= 1 means the input is never empty, so the result always has at least one part and you can read the first interval safely.

View on LeetCode

Hints

Hint 1

This is a greedy problem with a line sweep flavor.

Hint 2

Walk through the string and treat every index as a possible end of the current part.

Solution

Intuition

This is a greedy problem with a line sweep flavor. Each letter forces a claim on the string: everything from its first occurrence to its last occurrence must stay in one part. The question becomes where those claims overlap.

Picture a row of train cars where each letter is a coupling bar reaching from its first car to its last car. The variable end is the farthest bar still attached, and you may unhook the train only once the scan reaches that car.

Notice what a cut position needs. A cut after index i is legal only if no letter on the left of the cut also appears on the right. So the moment you add a letter to the current part, you learn that the part must stretch at least to that letter's last index. Every new letter can push that requirement farther right, never back left.

That gives the rule. Keep end, the largest last index among all letters in the current part. While the scan index is below end, some letter still has copies ahead, so you cannot cut. When the scan index equals end, every letter in the part has finished, and cutting here is legal.

Cutting at the first legal spot is also optimal. An early cut leaves the longest suffix for later parts, and the suffix is itself a fresh problem. Taking every legal cut gives the finest split, which is why the answer is unique.

Watch the pattern animation

Worked example

Input: s = "zzzzzzzzzzzzzzzzzzzz" (the letter z repeated 20 times)
Output: [20]
Explanation: Only one letter exists, and its occurrences span index 0 through 19. Any cut would separate two z characters, so the whole string is one part of size 20.

Approach 1: Brute force: test every cut

Walk through the string and treat every index as a possible end of the current part. For each candidate end, check whether any letter in the part also appears later in the string. If none does, the cut is legal, so you close the part and start the next one.

This is the direct translation of the rule "no letter may appear in two parts". It re-scans the whole remaining suffix for every candidate end, which is where the time goes.

Steps

  1. Set start = 0 and clear a 26-slot table inPart that marks letters in the current part.
  2. For each index end, mark s[end] as present in inPart.
  3. Scan every index j after end. If s[j] is marked in inPart, the cut is illegal, so stop scanning.
  4. If the scan finds no marked letter, record the size end - start + 1.
  5. After recording, set start = end + 1 and clear inPart.
  6. Return the recorded sizes.

Dry run

On z repeated 20 times. At end = 0, inPart holds z. The suffix scan reads index 1, finds z, and rejects the cut. The same happens for every end from 0 to 18, each time rejected after one comparison.

At end = 19 the suffix is empty, so no letter is found. The cut is legal and the recorded size is 19 - 0 + 1 = 20. The result is [20].

Complexity

TimeO(n^2)
SpaceO(1) extra, plus the output

Let n be the length of s. There are n candidate ends, and each one triggers a suffix scan of at most n characters, so the work is bounded by n * n. The bound is loose in practice because only 26 letters exist and the scan stops at the first conflict, but it still repeats scans that a lookup table removes. Space is the 26-slot table, which does not grow with n.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        n = len(s)
        result = []
        in_part = [False] * 26
        start = 0
        for end in range(n):
            in_part[ord(s[end]) - 97] = True
            ok = True
            # does any letter of the current part appear after end?
            for j in range(end + 1, n):
                if in_part[ord(s[j]) - 97]:
                    ok = False
                    break
            if ok:
                result.append(end - start + 1)
                start = end + 1
                in_part = [False] * 26
        return result

Approach 2: Letter intervals, then merge

What's slow: the brute force asks "does this letter appear later?" by scanning the suffix again and again. The answer for each letter never changes, so it should be computed once.

The insight that fixes it: one pass gives every letter a span, from its first index to its last index. Letters whose spans overlap must share a part. That is the classic merge-intervals problem, with at most 26 intervals.

Steps

  1. Make two arrays of size 26, first filled with -1 and last.
  2. Scan s once. Set first[c] the first time you see letter c, and set last[c] = i every time.
  3. Build one interval [first[c], last[c]] for each letter that appears.
  4. Sort the intervals by their start index.
  5. Walk the sorted list while holding a current interval. If the next interval starts after the current end, close the current one and record its size.
  6. Otherwise extend the current end to the larger of the two ends. After the loop, record the final interval.

Dry run

On z repeated 20 times. The scan sets first[z] = 0 and last[z] = 19. Only one letter exists, so the list is [[0, 19]].

Sorting changes nothing. The current interval starts as [0, 19] and there is no next interval to compare. The final step records 19 - 0 + 1 = 20, so the result is [20].

For contrast, abac gives a: [0,2], b: [1,1], c: [3,3]. Interval b starts at 1, which is not after 2, so it merges. Interval c starts at 3, which is after 2, so the first part closes with size 3. The result is [3, 1].

Complexity

TimeO(n)
SpaceO(1) extra, plus the output

Let n be the length of s. The scan touches each character once, costing n steps. At most 26 intervals exist, so sorting costs 26 * log 26 and merging costs 26, both constant. The arrays hold 26 entries each, so space does not depend on n.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        first = {}
        last = {}
        for i, c in enumerate(s):
            if c not in first:
                first[c] = i
            last[c] = i
        # one interval per letter, sorted by start
        intervals = sorted((first[c], last[c]) for c in first)
        result = []
        cur_start, cur_end = intervals[0]
        for a, b in intervals[1:]:
            if a > cur_end:
                result.append(cur_end - cur_start + 1)
                cur_start, cur_end = a, b
            else:
                cur_end = max(cur_end, b)
        result.append(cur_end - cur_start + 1)
        return result
Line Sweep pattern infographic for Partition Labels

Solution pattern

Line Sweep

Part of Greedy Patterns

Approach 3: One-pass greedy sweep with last indicesOptimalLine Sweep

What's slow: the interval method stores a first index it does not need and sorts intervals that are already in string order. The sweep itself visits indices in order, so the sorting step repeats information the scan gives for free.

The insight that fixes it: you only need each letter's last index. Sweep left to right and keep end, the farthest last index of any letter seen in the current part. When the index reaches end, cut. No sorting and no first indices are needed.

Steps

  1. Scan s once and store last[c] = i for every letter, so each slot ends up with the final index.
  2. Set start = 0 and end = 0, and create an empty result list.
  3. Sweep i from 0 to n - 1. Update end = max(end, last[s[i]]).
  4. If i == end, every letter in the part has finished.
  5. Append i - start + 1 to the result.
  6. Set start = i + 1 so the next part begins right after the cut.
  7. Return the result list.

Dry run

On z repeated 20 times. First pass: last[z] = 19. Second pass, with start = 0 and end = 0 initially:

is[i]last[s[i]]end after maxi == end?action
0z1919nokeep going
1z1919nokeep going
2z1919nokeep going
3 to 18z1919nokeep going
19z1919yesappend 19 - 0 + 1 = 20, start = 20

The result is [20].

On abac the first pass gives a: 2, b: 1, c: 3. At i = 0, end = 2. At i = 1, b gives 1, so end stays 2. At i = 2, the index equals end, so append 3. At i = 3, end = 3 and i == end, so append 1. The result is [3, 1].

Complexity

TimeO(n)
SpaceO(1) extra, plus the output

Let n be the length of s. The first loop does one write per character and the second loop does one lookup, one max and one comparison per character, so the total is about 2n constant-time steps. The last table has 26 slots no matter how long s is. The result list holds one integer per part, at most 26 of them, since each part must contain a letter that appears in no other part.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def partitionLabels(self, s: str) -> List[int]:
        # last index of every letter
        last = {c: i for i, c in enumerate(s)}
        result = []
        start = 0
        end = 0
        for i, c in enumerate(s):
            end = max(end, last[c])
            if i == end:
                result.append(i - start + 1)
                start = i + 1
        return result

Common mistakes

  • Writing end = last[c] instead of end = max(end, last[c]). A later letter with an earlier last index then shrinks the boundary and you cut too soon. Use the maximum so the boundary only moves right.
  • Cutting when i == last[s[i]] alone. That checks only the current letter, so abac would cut at index 1 after b. Compare i with the running end for the whole part.
  • Forgetting start = i + 1 after a cut. The next size is then measured from the old start and comes out too large. Move start right after every recorded part.
  • Computing the size as i - start. Both ends are inclusive, so the size is i - start + 1. A single-character part would otherwise have size 0.
  • Building last inside the same loop as the sweep. At index i you would only know the last occurrence so far, not the true one. Finish the first pass over the whole string before the sweep begins.
  • In the interval approach, sorting by end index instead of start index. The merge step assumes intervals arrive in order of their starts, so sort by first[c].

Edge cases

  • s = "a" returns [1]. The only interval is [0, 0], so the sweep cuts at index 0.
  • All identical letters, such as zzzzzzzzzzzzzzzzzzzz, return [n]. One letter spans the whole string and no cut is legal before the last index.
  • All distinct letters, such as abc, return [1,1,1]. Each letter's last index equals its own index, so every position is a cut.
  • s = "abab" returns [4]. The a span reaches index 2 and the b span reaches index 3, so end grows to 3 before any cut.
  • s = "caedbdedda" returns [1,9]. The letter c appears once and closes at index 0, while a at index 1 and index 9 pulls the rest into one part.
  • A string of 10^5 characters must finish in two linear passes. Any approach that rescans the suffix per index risks a timeout.

Follow-ups interviewers ask

What if the alphabet is large, such as full Unicode, instead of 26 letters?
Replace the 26-slot array with a hash map from character to last index. Time stays O(n) on average. Space becomes O(k), where k is the number of distinct characters. The sweep logic does not change.
What if the string is too large for memory and arrives from disk?
Read it in two passes. The first pass fills the last-index table, which is small. The second pass streams the characters and emits a part size each time the index reaches end. A single pass cannot work, because a cut depends on whether a letter appears later, and you cannot know that before reading it.
Why is the best partition unique, and why does cutting early give the maximum count?
A cut after index i is legal exactly when no letter spans across it. That test depends only on the string, not on other cuts. So the set of legal cuts is fixed, and using all of them gives the finest partition. Any other valid partition uses a subset of those cuts, so it has fewer parts.

Partition Labels FAQ

What is the time complexity of Partition Labels?

The greedy sweep runs in O(n), where n is the length of the string. One pass fills the last-index table and one pass does the sweep, each doing constant work per character. The brute force that rescans the suffix for every cut is O(n^2) as a bound.

Why use a last-occurrence table for Partition Labels?

A cut is legal only if no letter in the current part appears later. The last index of a letter answers that in constant time. Without the table you rescan the suffix for every candidate cut, which repeats the same work.

Why use the maximum when updating the end boundary?

A part may contain several letters, and each one requires the part to reach its own last index. The farthest of those requirements decides where the part can finish. Using the maximum guarantees no letter is left with copies outside the part.

Can Partition Labels be solved in O(1) extra space?

Yes, if you do not count the output. The lookup table has 26 entries, which is a constant. You can drop the table by searching for the last occurrence of each letter with a reverse scan, but that costs O(n^2) time in the worst case.

Is Partition Labels a greedy or a two pointers problem?

It is greedy, with a two-pointer feel. The start pointer marks where the current part begins and the sweep index advances to the boundary end. The greedy part is cutting at the earliest legal index.

How do I write the Partition Labels solution in Python or Java?

Build the last-index table, then sweep with start and end. In Python, {c: i for i, c in enumerate(s)} builds the table in one line. In Java, use an int[26] and copy the result list into an int[] before returning.

Asked at

See which companies ask this — Pro

Practise it