Python coding

Most pieces with no shared letters

Cut the string s into as many contiguous pieces as possible so that every letter appears in only one piece: all copies of a letter land in the same piece. Return the lengths of the pieces, from left to right.

s holds only lowercase letters and may be empty (return []). Aim for O(n) time.

Besides the tests, one large input (a 12,000-letter string) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • piece_sizes("abacbdeffe") → [5,1,4]
  • piece_sizes("abcd") → [1,1,1,1]
  • piece_sizes("abcda") → [5]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

First record where each letter appears for the last time. A piece that contains a letter must stretch at least to that position.

Hint 2

Scan left to right keeping end, the farthest last position of any letter in the current piece. When the index reaches end, close the piece there and start a new one.

Hint 3

The trap is closing a piece when a letter's first run ends: in "abab" the a comes back later, so the whole string is one piece.

Solution and why it works
pythonO(n) · O(k), k = distinct letters (at most 26)
def piece_sizes(s: str) -> list[int]:
    last = {ch: i for i, ch in enumerate(s)}   # last position of each letter
    sizes, start, end = [], 0, 0
    for i, ch in enumerate(s):
        end = max(end, last[ch])         # this piece must reach every last copy
        if i == end:                     # earliest legal cut: take it
            sizes.append(i - start + 1)
            start = i + 1
    return sizes

A piece that holds a letter must reach that letter's last position, so end, the farthest last position among the letters seen in the current piece, is the earliest place it can close. Closing there is safe: an earlier cut is illegal, and cutting as early as possible leaves every later cut available. One pass records last positions and one pass cuts: O(n) time. The trap is testing every cut by comparing the letters on both sides, which is O(n²).