Parcel Line Into Trucks

MediumgreedyAlso known as Partition Labels

At a sorting depot, parcels come off a conveyor belt in a fixed order, each stamped with a one-letter code for its destination town. Loaders fill trucks straight from the belt: the first few parcels on truck 1, the next few on truck 2, and so on, with no reordering.

All parcels for a town must go on the same truck. Within that rule, the depot wants as many trucks as possible, because smaller loads leave sooner.

Your task

Write truckLoads(tags). tags is a string of lowercase letters, one per parcel, in belt order. Cut it into as many consecutive pieces as possible so that every letter appears in only one piece. Return the lengths of the pieces, in order.

An empty string returns an empty list.

truckLoads(tags: string) → int[]

Examples

Example 1
Input
tags = "kbkmzmqq"
Output
[3, 3, 2]
Why

The k parcels are at positions 0 and 2, so the first truck takes at least "kbk". Nothing in it appears later, so cut there. Then "mzm" holds both m parcels, then "qq".

Example 2
Input
tags = "abccbadd"
Output
[6, 2]
Why

The a parcels are at positions 0 and 5, so the first truck takes positions 0 to 5, which covers every b and c too. Then "dd". Cutting after "abc" would split the a parcels across two trucks.

Constraints

  • 0 ≤ tags.length ≤ 10,000
  • tags contains only the letters a to z
Start with brute force

At every possible cut position, check whether the letters on the left and right are disjoint. Every such position is a safe cut, and cutting at all of them gives the most pieces. Building the two sets costs O(n) per position, so this is O(n²): around 100 million steps for 10,000 parcels.

Each letter's last position answers the same question as you walk, without rebuilding sets.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code