15% off all plans & roadmaps Use code
See plansPartition Labels
- LeetCode 763
- Medium
- Greedy Patterns
- Line Sweep
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^5scontains 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
nup 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 >= 1means the input is never empty, so the result always has at least one part and you can read the first interval safely.
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.
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
- Set
start = 0and clear a 26-slot tableinPartthat marks letters in the current part. - For each index
end, marks[end]as present ininPart. - Scan every index
jafterend. Ifs[j]is marked ininPart, the cut is illegal, so stop scanning. - If the scan finds no marked letter, record the size
end - start + 1. - After recording, set
start = end + 1and clearinPart. - 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
| Time | O(n^2) |
|---|---|
| Space | O(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 resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] partitionLabels(String s) {
int n = s.length();
List<Integer> result = new ArrayList<>();
boolean[] inPart = new boolean[26];
int start = 0;
for (int end = 0; end < n; end++) {
inPart[s.charAt(end) - 'a'] = true;
boolean ok = true;
// does any letter of the current part appear after end?
for (int j = end + 1; j < n; j++) {
if (inPart[s.charAt(j) - 'a']) {
ok = false;
break;
}
}
if (ok) {
result.add(end - start + 1);
start = end + 1;
inPart = new boolean[26];
}
}
int[] answer = new int[result.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = result.get(i);
}
return answer;
}
};C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> partitionLabels(string s) {
int n = s.size();
vector<int> result;
vector<bool> inPart(26, false);
int start = 0;
for (int end = 0; end < n; end++) {
inPart[s[end] - 'a'] = true;
bool ok = true;
// does any letter of the current part appear after end?
for (int j = end + 1; j < n; j++) {
if (inPart[s[j] - 'a']) {
ok = false;
break;
}
}
if (ok) {
result.push_back(end - start + 1);
start = end + 1;
fill(inPart.begin(), inPart.end(), false);
}
}
return result;
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {number[]}
*/
var partitionLabels = function(s) {
const n = s.length;
const result = [];
let inPart = new Array(26).fill(false);
let start = 0;
for (let end = 0; end < n; end++) {
inPart[s.charCodeAt(end) - 97] = true;
let ok = true;
// does any letter of the current part appear after end?
for (let j = end + 1; j < n; j++) {
if (inPart[s.charCodeAt(j) - 97]) {
ok = false;
break;
}
}
if (ok) {
result.push(end - start + 1);
start = end + 1;
inPart = new Array(26).fill(false);
}
}
return result;
};GoTested in our runner
func partitionLabels(s string) []int {
n := len(s)
result := []int{}
var inPart [26]bool
start := 0
for end := 0; end < n; end++ {
inPart[s[end]-'a'] = true
ok := true
// does any letter of the current part appear after end?
for j := end + 1; j < n; j++ {
if inPart[s[j]-'a'] {
ok = false
break
}
}
if ok {
result = append(result, end-start+1)
start = end + 1
inPart = [26]bool{}
}
}
return result
}C#Tested in our runner
public class Solution {
public int[] partitionLabels(string s) {
int n = s.Length;
var result = new List<int>();
bool[] inPart = new bool[26];
int start = 0;
for (int end = 0; end < n; end++) {
inPart[s[end] - 'a'] = true;
bool ok = true;
// does any letter of the current part appear after end?
for (int j = end + 1; j < n; j++) {
if (inPart[s[j] - 'a']) {
ok = false;
break;
}
}
if (ok) {
result.Add(end - start + 1);
start = end + 1;
inPart = new bool[26];
}
}
return result.ToArray();
}
}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
- Make two arrays of size 26,
firstfilled with -1 andlast. - Scan
sonce. Setfirst[c]the first time you see letterc, and setlast[c] = ievery time. - Build one interval
[first[c], last[c]]for each letter that appears. - Sort the intervals by their start index.
- 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.
- 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
| Time | O(n) |
|---|---|
| Space | O(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 resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] partitionLabels(String s) {
int[] first = new int[26];
int[] last = new int[26];
Arrays.fill(first, -1);
for (int i = 0; i < s.length(); i++) {
int c = s.charAt(i) - 'a';
if (first[c] == -1) {
first[c] = i;
}
last[c] = i;
}
// one interval per letter, sorted by start
List<int[]> intervals = new ArrayList<>();
for (int c = 0; c < 26; c++) {
if (first[c] != -1) {
intervals.add(new int[]{first[c], last[c]});
}
}
intervals.sort((x, y) -> x[0] - y[0]);
List<Integer> result = new ArrayList<>();
int curStart = intervals.get(0)[0];
int curEnd = intervals.get(0)[1];
for (int k = 1; k < intervals.size(); k++) {
int[] iv = intervals.get(k);
if (iv[0] > curEnd) {
result.add(curEnd - curStart + 1);
curStart = iv[0];
curEnd = iv[1];
} else {
curEnd = Math.max(curEnd, iv[1]);
}
}
result.add(curEnd - curStart + 1);
int[] answer = new int[result.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = result.get(i);
}
return answer;
}
};C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> partitionLabels(string s) {
int n = s.size();
vector<int> first(26, -1), last(26, -1);
for (int i = 0; i < n; i++) {
int c = s[i] - 'a';
if (first[c] == -1) {
first[c] = i;
}
last[c] = i;
}
// one interval per letter, sorted by start
vector<pair<int, int>> intervals;
for (int c = 0; c < 26; c++) {
if (first[c] != -1) {
intervals.push_back({first[c], last[c]});
}
}
sort(intervals.begin(), intervals.end());
vector<int> result;
int curStart = intervals[0].first;
int curEnd = intervals[0].second;
for (size_t k = 1; k < intervals.size(); k++) {
if (intervals[k].first > curEnd) {
result.push_back(curEnd - curStart + 1);
curStart = intervals[k].first;
curEnd = intervals[k].second;
} else {
curEnd = max(curEnd, intervals[k].second);
}
}
result.push_back(curEnd - curStart + 1);
return result;
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {number[]}
*/
var partitionLabels = function(s) {
const first = new Array(26).fill(-1);
const last = new Array(26).fill(-1);
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i) - 97;
if (first[c] === -1) {
first[c] = i;
}
last[c] = i;
}
// one interval per letter, sorted by start
const intervals = [];
for (let c = 0; c < 26; c++) {
if (first[c] !== -1) {
intervals.push([first[c], last[c]]);
}
}
intervals.sort((a, b) => a[0] - b[0]);
const result = [];
let curStart = intervals[0][0];
let curEnd = intervals[0][1];
for (let k = 1; k < intervals.length; k++) {
const [a, b] = intervals[k];
if (a > curEnd) {
result.push(curEnd - curStart + 1);
curStart = a;
curEnd = b;
} else {
curEnd = Math.max(curEnd, b);
}
}
result.push(curEnd - curStart + 1);
return result;
};GoTested in our runner
import "sort"
func partitionLabels(s string) []int {
var first, last [26]int
for c := 0; c < 26; c++ {
first[c] = -1
}
for i := 0; i < len(s); i++ {
c := s[i] - 'a'
if first[c] == -1 {
first[c] = i
}
last[c] = i
}
// one interval per letter, sorted by start
intervals := [][2]int{}
for c := 0; c < 26; c++ {
if first[c] != -1 {
intervals = append(intervals, [2]int{first[c], last[c]})
}
}
sort.Slice(intervals, func(a, b int) bool {
return intervals[a][0] < intervals[b][0]
})
result := []int{}
curStart, curEnd := intervals[0][0], intervals[0][1]
for k := 1; k < len(intervals); k++ {
if intervals[k][0] > curEnd {
result = append(result, curEnd-curStart+1)
curStart, curEnd = intervals[k][0], intervals[k][1]
} else if intervals[k][1] > curEnd {
curEnd = intervals[k][1]
}
}
result = append(result, curEnd-curStart+1)
return result
}C#Tested in our runner
public class Solution {
public int[] partitionLabels(string s) {
int[] first = new int[26];
int[] last = new int[26];
Array.Fill(first, -1);
for (int i = 0; i < s.Length; i++) {
int c = s[i] - 'a';
if (first[c] == -1) {
first[c] = i;
}
last[c] = i;
}
// one interval per letter, sorted by start
var intervals = new List<int[]>();
for (int c = 0; c < 26; c++) {
if (first[c] != -1) {
intervals.Add(new int[] { first[c], last[c] });
}
}
intervals.Sort((x, y) => x[0].CompareTo(y[0]));
var result = new List<int>();
int curStart = intervals[0][0];
int curEnd = intervals[0][1];
for (int k = 1; k < intervals.Count; k++) {
if (intervals[k][0] > curEnd) {
result.Add(curEnd - curStart + 1);
curStart = intervals[k][0];
curEnd = intervals[k][1];
} else {
curEnd = Math.Max(curEnd, intervals[k][1]);
}
}
result.Add(curEnd - curStart + 1);
return result.ToArray();
}
}
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
- Scan
sonce and storelast[c] = ifor every letter, so each slot ends up with the final index. - Set
start = 0andend = 0, and create an empty result list. - Sweep
ifrom 0 ton - 1. Updateend = max(end, last[s[i]]). - If
i == end, every letter in the part has finished. - Append
i - start + 1to the result. - Set
start = i + 1so the next part begins right after the cut. - 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:
| i | s[i] | last[s[i]] | end after max | i == end? | action |
|---|---|---|---|---|---|
| 0 | z | 19 | 19 | no | keep going |
| 1 | z | 19 | 19 | no | keep going |
| 2 | z | 19 | 19 | no | keep going |
| 3 to 18 | z | 19 | 19 | no | keep going |
| 19 | z | 19 | 19 | yes | append 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
| Time | O(n) |
|---|---|
| Space | O(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 resultJavaTested in our runner
import java.util.*;
class Solution {
public int[] partitionLabels(String s) {
int n = s.length();
int[] last = new int[26];
for (int i = 0; i < n; i++) {
last[s.charAt(i) - 'a'] = i;
}
List<Integer> result = new ArrayList<>();
int start = 0;
int end = 0;
for (int i = 0; i < n; i++) {
end = Math.max(end, last[s.charAt(i) - 'a']);
if (i == end) {
result.add(i - start + 1);
start = i + 1;
}
}
int[] answer = new int[result.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = result.get(i);
}
return answer;
}
};C++Tested in our runner
using namespace std;
class Solution {
public:
vector<int> partitionLabels(string s) {
int n = s.size();
vector<int> last(26, 0);
for (int i = 0; i < n; i++) {
last[s[i] - 'a'] = i;
}
vector<int> result;
int start = 0;
int end = 0;
for (int i = 0; i < n; i++) {
end = max(end, last[s[i] - 'a']);
if (i == end) {
result.push_back(i - start + 1);
start = i + 1;
}
}
return result;
}
};JavaScriptTested in our runner
/**
* @param {string} s
* @return {number[]}
*/
var partitionLabels = function(s) {
const n = s.length;
const last = new Array(26).fill(0);
for (let i = 0; i < n; i++) {
last[s.charCodeAt(i) - 97] = i;
}
const result = [];
let start = 0;
let end = 0;
for (let i = 0; i < n; i++) {
end = Math.max(end, last[s.charCodeAt(i) - 97]);
if (i === end) {
result.push(i - start + 1);
start = i + 1;
}
}
return result;
};GoTested in our runner
func partitionLabels(s string) []int {
var last [26]int
for i := 0; i < len(s); i++ {
last[s[i]-'a'] = i
}
result := []int{}
start, end := 0, 0
for i := 0; i < len(s); i++ {
if last[s[i]-'a'] > end {
end = last[s[i]-'a']
}
if i == end {
result = append(result, i-start+1)
start = i + 1
}
}
return result
}C#Tested in our runner
public class Solution {
public int[] partitionLabels(string s) {
int n = s.Length;
int[] last = new int[26];
for (int i = 0; i < n; i++) {
last[s[i] - 'a'] = i;
}
var result = new List<int>();
int start = 0;
int end = 0;
for (int i = 0; i < n; i++) {
end = Math.Max(end, last[s[i] - 'a']);
if (i == end) {
result.Add(i - start + 1);
start = i + 1;
}
}
return result.ToArray();
}
}Common mistakes
- Writing
end = last[c]instead ofend = 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, soabacwould cut at index 1 afterb. Compareiwith the runningendfor the whole part. - Forgetting
start = i + 1after a cut. The next size is then measured from the old start and comes out too large. Movestartright after every recorded part. - Computing the size as
i - start. Both ends are inclusive, so the size isi - start + 1. A single-character part would otherwise have size 0. - Building
lastinside the same loop as the sweep. At indexiyou 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]. Theaspan reaches index 2 and thebspan reaches index 3, soendgrows to 3 before any cut.s = "caedbdedda"returns[1,9]. The lettercappears once and closes at index 0, whileaat 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
Related problems
- Car Pooling · same technique: Line Sweep
- Interval List Intersections · same technique: Line Sweep
- Employee Free Time · same technique: Line Sweep
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns
- Insert Interval · same pattern: Greedy Patterns
- Jump Game II · same pattern: Greedy Patterns