Parcel-delivery app~15 min2s · 256 MBtarget O(n) time, O(1) spacestrings
A warehouse has a loop-shaped conveyor belt. Parcels ride on it, and each carries a one-letter label for its destination. The belt is a loop, so the last parcel is followed by the first one again.
A loader wants the longest stretch of parcels that all carry the same letter, so that one worker can take them in one go. The stretch may cross the point where the list of parcels starts.
Write longest_belt_stripe(belt).
belt is a non-empty string of lowercase letters, one for each parcel, in the order they ride on the belt. After the last letter comes the first letter again.Input: belt = "aabbbcaa"
Output: 4Read along the string: aa, bbb, c, aa. On the loop, the last aa is followed by the first aa, so together they make one stripe of 4.
To avoid cutting a stripe at the start of the string, begin where a stripe starts. That is a letter that differs from the one before it, going round the loop. Here it is index 2, the first b.
Then scan all 8 letters once, round the loop.
| Step | Index | Letter | Same as the one before? | Stripe length | Longest |
|---|---|---|---|---|---|
| 1 | 2 | b |
no | 1 | 1 |
| 2 | 3 | b |
yes | 2 | 2 |
| 3 | 4 | b |
yes | 3 | 3 |
| 4 | 5 | c |
no | 1 | 3 |
| 5 | 6 | a |
no | 1 | 3 |
| 6 | 7 | a |
yes | 2 | 3 |
| 7 | 0 | a |
yes | 3 | 3 |
| 8 | 1 | a |
yes | 4 | 4 |
The longest stripe has 4 parcels.
Input: belt = "abab"
Output: 1Neighbouring letters always differ, so every stripe has 1 parcel.
Input: belt = "kkkk"
Output: 4Every parcel carries k. The stripe is the whole belt, which has 4 parcels.
1 ≤ length of belt ≤ 10^5belt has only lowercase letters a to zCounting the stripe from every parcel costs up to n steps per parcel. On a belt with long stripes that is about n^2 = 10^10 steps, too slow for 2 seconds.
A single pass over the belt is enough: n steps, 10^5 at most. The answer is at most n, so a 32-bit integer holds it.