Algo-Sim › Greedy
Partition Labels
Medium · Greedy · step through it in Java, Python and C++ on your own input
Cut the string into as many parts as possible so each letter appears in only one part. Stretch the current part to the last copy of every letter in it.
Problem
Split the string s into as many consecutive pieces as possible so that each letter appears in at most one piece. Return the lengths of the pieces in order.
Constraints
- 1 ≤ s.length ≤ 500
- s contains only lowercase English letters
Edge cases to test
- One letter repeated: one part
- All letters different: n parts of size 1
- The first letter also ends the string
Follow-up questions
- Why is cutting as soon as possible optimal?
- A part can end only where every letter in it has finished; the earliest such point leaves the most room for later cuts.
- How is this related to merging intervals?
- Each letter’s first-to-last range is an interval; the parts are the merged blocks of those intervals.
Solution
Java
public List<Integer> partitionLabels(String s) {
int[] last = new int[26];
for (int i = 0; i < s.length(); i++) last[s.charAt(i) - 'a'] = i;
List<Integer> sizes = new ArrayList<>();
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) {
sizes.add(end - start + 1);
start = i + 1;
}
}
return sizes;
}Python
def partition_labels(s):
last = {c: i for i, c in enumerate(s)}
sizes = []
start = end = 0
for i, c in enumerate(s):
end = max(end, last[c])
if i == end:
sizes.append(end - start + 1)
start = i + 1
return sizesC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> partitionLabels(string &s) {
vector<int> last = vector<int>(26);
for (int i = 0; i < int(s.size()); i++)
last[s[i] - 'a'] = i;
vector<int> sizes = {};
int start = 0, end = 0;
for (int i = 0; i < int(s.size()); i++) {
end = std::max(end, last[s[i] - 'a']);
if (i == end) {
sizes.push_back(end - start + 1);
start = i + 1;
}
}
return sizes;
}
};
More Greedy problems
- Maximum Subarray (Medium)
- Best Time to Buy and Sell Stock II (Medium)
- Jump Game (Medium)
- Jump Game II (Medium)
- Gas Station (Medium)
- Task Scheduler (Medium)
- Hand of Straights (Medium)
- Merge Triplets to Form Target Triplet (Medium)
- Valid Parenthesis String (Medium)
- Minimum Number of Arrows to Burst Balloons (Medium)
- Candy (Hard)
- Boats to Save People (Medium)
- Two City Scheduling (Medium)