Problem 580752 · medium · Phase 05 Advanced Algorithms & Graphs

Pack Each Label in One Box

greedy · strings · last occurrence

A conveyor carries parcels marked with lowercase labels, given as the string labels. You must cut the conveyor into consecutive pieces so that every label appears in at most one piece, and you want as many pieces as possible. Return the list of piece lengths from left to right.

Examples

Input:  labels = "abcbdeefe"
Output: [1, 3, 1, 4]
Explanation: "a" | "bcb" | "d" | "eefe". Every label lives in one piece.
Input:  labels = "xyxz"
Output: [3, 1]

Constraints

  • 0 <= len(labels) <= 10**5, lowercase letters only.
  • An empty string gives [].
  • Target complexity: O(n) time, O(1) extra space (26 letters).

Goals

  • Record the last position of every character in one pass
  • Grow the current piece until it covers the last copy of everything inside it
  • Cut as early as possible to maximise the number of pieces
Starting Python…