Start learning free

LESSON 548 OF 673 · GREEDY

Partition Labels in Python: O(n) Greedy with Last Occurrences

Practice O(n) Read the full explanation

You get a string s of lowercase letters.

Cut s into as many parts as you can. Return a list with the size of each part, from left to right.

Each letter may appear in only one part. So if one part has an a, no other part can have one.

The parts keep the letters in order. Put back together, they give s again.

 

Example 1:

Input: s = "noonlevelradar"
Output: [4,5,5]
Explanation: The parts are "noon", "level" and "radar".
No letter shows up in two of them.
A cut inside "noon" would split its two n's.

Example 2:

Input: s = "mississippi"
Output: [1,10]
Explanation: The parts are "m" and "ississippi".
The m appears only once, so it is a part alone.
The first i is at index 1, and the last i is the final letter.
So "ississippi" can't be cut.

Example 3:

Input: s = "world"
Output: [1,1,1,1,1]
Explanation: Every letter appears once.
So each letter is a part of its own.

 

Constraints:

  • s has 1 to 100,000 letters.
  • Each letter is from a to z.

Note:

Your solution should run in O(n) time.

STEP 1 OF 12
    Ctrl + Enter to check

    PYTHON · GREEDY

    Partition Labels in Python, explained

    Problem overview

    The method partitionLabels receives a string s of lowercase letters. Cut it into as many parts as possible so that each letter appears in only one part. The parts keep the letters in order, so joining them gives s back. The method returns a list with the size of each part, from left to right.

    For s = "noonlevelradar" the answer is [4, 5, 5], with the parts "noon", "level" and "radar". No letter shows up in two of them. A cut inside "noon" would put one n on each side. For "mississippi" the answer is [1, 10]: the m appears once, so it stands alone, while the first i is at index 1 and the last one is the final letter, so "ississippi" cannot be cut. For "world", every letter is unique and the answer is [1, 1, 1, 1, 1].

    The lesson asks for O(n) time, with up to 100,000 letters.

    Approach: extend the part to cover each letter's last copy

    Trying every set of cut positions is exponential. Think about the first part instead. It starts at index 0 and contains the first letter, so it must also contain the last copy of that letter. But every letter between those two spots belongs to the part now, and each of them drags in its own last copy, which may be even further right. The part ends at the first index where nothing inside it has a copy further right.

    That suggests two passes:

    1. Record the last index of every letter.
    2. Walk through the string keeping end, the furthest last-copy index of any letter in the current part. When the current index reaches end, nothing in the part appears later, so a cut is safe.

    Cutting as early as possible is also what gives the most parts: a later cut would only swallow letters that could have started their own parts.

    Step by step

    1. Create last = [0] * 26. One slot per letter: slot 0 for a, slot 1 for b and so on.
    2. First pass: loop with i over range(len(s)).
    3. Store the index: last[ord(s[i]) - ord('a')] = i. ord gives a character's code, and the codes of a to z are consecutive, so the subtraction gives 0 for a up to 25 for z. A later i overwrites an earlier one, so after the loop each slot holds the last index of its letter.
    4. Create sizes = [] for the answer.
    5. Create start = 0, where the current part begins.
    6. Create end = 0, the furthest index the current part must reach.
    7. Second pass: loop with i over range(len(s)) again.
    8. Grow the part: end = max(end, last[ord(s[i]) - ord('a')]). The part holding this letter must hold its last copy.
    9. Check for a cut: if i == end.
    10. Record the size: append end - start + 1 to sizes. Both ends are included, hence the + 1.
    11. Start the next part right after this one: start = i + 1.
    12. Return sizes. At the last index end cannot be larger than i, so the loop always finishes with a cut.

    For "noonlevelradar", the first pass gives these last indexes:

    a: 12  d: 11  e: 7  l: 8  n: 3  o: 2  r: 13  v: 6

    The second pass then goes like this:

    0 n end 3
    1 o end 3
    2 o end 3
    3 n end 3 cut
    4 l end 8
    5 e end 8
    6 v end 8
    7 e end 8
    8 l end 8 cut
    9 r end 13
    10 a end 13
    11 d end 13
    12 a end 13
    13 r end 13 cut

    The cuts happen at indexes 3, 8 and 13, so the sizes are 4, 5 and 5.

    The solution in Python

    class Solution:
        def partitionLabels(self, s: str) -> List[int]:
            last = [0] * 26
            for i in range(len(s)):
                last[ord(s[i]) - ord('a')] = i
            sizes = []
            start = 0
            end = 0
            for i in range(len(s)):
                end = max(end, last[ord(s[i]) - ord('a')])
                if i == end:
                    sizes.append(end - start + 1)
                    start = i + 1
            return sizes
    

    Python details worth knowing:

    • [0] * 26 builds a list of 26 zeros. That is safe here because integers are immutable; the same trick with a list of lists would share one inner list.
    • Strings in Python are immutable and indexable, so s[i] is a one-character string, and ord turns it into its code.
    • The two loops are separate on purpose. The second one needs the final last table, so it cannot start until the first pass has seen the whole string.

    Complexity

    Time: O(n). Two passes over the string, with constant work per character.

    Space: O(1) besides the answer. The table has 26 slots whatever the length of the string. The returned list holds one number per part.

    Edge cases and common mistakes

    • A string of one letter. "a" gives [1].
    • One letter repeated across the whole string. "abcab" gives [5]: the a at index 0 reaches index 3, the b inside it reaches index 4, and the part cannot end earlier.
    • Cutting at the first copy of a letter. A table of first indexes says nothing about where a letter shows up again, so a part could end before the later copies of its letters. The table must hold last indexes.
    • Forgetting + 1 in the size. A part from index start to index end holds end - start + 1 letters.
    • Forgetting to reset start. The next part must begin at i + 1, or later sizes grow too large.

    Testing

    Results from running the method:

    sResult
    "noonlevelradar"[4, 5, 5]
    "mississippi"[1, 10]
    "world"[1, 1, 1, 1, 1]
    "abcab"[5]
    "a"[1]
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free