Practice › Greedy
Partition Labels
Medium · Greedy · Asked at Amazon, Meta, Google, Microsoft
Split the string into as many parts as possible so that each letter appears in at most one part. Print the sizes of the parts from left to right.
Input
A single line with the string (lowercase letters).
Output
The part sizes, space-separated.
Constraints
- 1 ≤ length ≤ 10^5
Record the last position of every letter. Sweep left to right extending the current part’s end to the last position of each letter seen; when the index reaches that end, the part closes.
Example 1
Input
ababcbacadefegdehijhklij
Output
9 7 8
Example 2
Input
eccbbbbdec
Output
10
Hints
- A part that contains a letter must reach that letter’s last occurrence.
- Record the last index of every letter first.
- Sweep, stretching the current part’s end; close the part when you reach its end.
Approach
last[c] = the last position of letter c. Walk i from 0, keeping end = max(end, last[s[i]]). When i == end, every letter inside [start, end] has all its occurrences inside, so close the part (size end − start + 1) and start a new one at i + 1. Closing as early as possible gives the most parts.
Complexity: O(n) time · O(26) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
cin >> s;
int last[26];
for (int i = 0; i < (int) s.size(); i++) last[s[i] - 'a'] = i;
string out;
int start = 0, end = 0;
for (int i = 0; i < (int) s.size(); i++) {
end = max(end, last[s[i] - 'a']);
if (i == end) {
out += (out.empty() ? "" : " ") + to_string(end - start + 1);
start = i + 1;
}
}
cout << out << "\n";
return 0;
}Python solution
s = input().strip()
last = {c: i for i, c in enumerate(s)}
out = []
start = end = 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end:
out.append(end - start + 1)
start = i + 1
print(*out)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
int[] last = new int[26];
for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
StringBuilder sb = new StringBuilder();
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
end = Math.max(end, last[s.charAt(i) - 'a']);
if (i == end) {
if (sb.length() > 0) sb.append(' ');
sb.append(end - start + 1);
start = i + 1;
}
}
System.out.println(sb);
}
}