Imagine you have a string representing a sequence of tasks, and you want to split it into as many parts as possible so that each task appears in only one part, making scheduling easier.
Given a string s, partition it into as many parts as possible so that each letter appears in at most one part. Return a list of integers representing the size of these parts.
1 ≤ s.length ≤ 10^5s consists of lowercase English letters only
Edge cases: Single character string → [1]All characters unique → each character forms a partition of size 1All characters the same → one partition of size n
def partitionLabels(s: str) -> list:public List<Integer> partitionLabels(String s)vector<int> partitionLabels(string s)function partitionLabels(s)
def partitionLabels(s):
# Write your solution here
pass
class Solution {
public List<Integer> partitionLabels(String s) {
// Write your solution here
return new ArrayList<>();
}
}
#include <vector>
#include <string>
using namespace std;
vector<int> partitionLabels(string s) {
// Write your solution here
return {};
}
function partitionLabels(s) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: [1,1,1,1,1]Incorrectly splitting partitions at every character without considering last occurrences.✅ Use a map to track last occurrence of each character and extend partition end to max last occurrence.
Wrong: [9,7,7]Off-by-one error in partition size calculation (missing +1).✅ Calculate partition size as end_index - start_index + 1.
Wrong: [1,8,7,8]Greedy trap: splitting partitions too early without extending to last occurrence of all characters.✅ Update partition end to max last occurrence of all characters seen so far before splitting.
Wrong: [9,7]Overlapping partitions due to misunderstanding partition constraints; characters appear in multiple partitions.✅ Ensure partitions are disjoint by using last occurrence boundaries to split.
Wrong: Timeout or crash on large inputUsing brute force or nested loops causing O(n^2) or worse complexity.✅ Implement O(n) solution using last occurrence map and single pass greedy partitioning.