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

Edge cases to test

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 sizes

C++

#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