Parcel Line Into Trucks

MediumgreedyAlso known as Partition Labels

At a sorting depot, parcels come off a conveyor belt in a fixed order. Each parcel is stamped with a one-letter code for its destination town. The loaders fill trucks straight from the belt: the first few parcels go on truck 1, the next few on truck 2, and so on, without reordering anything.

Each town should be served by exactly one truck, so all parcels for a town must end up 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 sit at positions 0 and 2, so the first truck takes at least "kbk". Nothing in "kbk" appears later, so cut there. Next, "mzm" holds both m parcels, then "qq". Three trucks: 3, 3 and 2 parcels.

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

The first a is at position 0 and the last a at position 5, so the first truck must take positions 0 to 5, which also covers every b and c. Then "dd" is the second truck. 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

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

The repeated work is rebuilding the sets. Knowing just each letter's last position answers the same question as you walk.

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