Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-796string-algorithms
A parcel carousel in a warehouse holds n labelled trays in a ring, and each label is a lowercase letter. One turn moves the carousel by one tray, to the left or to the right.
The packing team has a target order of labels, and each turn costs time. Your team lead asks: "What is the fewest number of single turns that brings the carousel to the target, in either direction?"
Write fewest_turns(start, goal).
start is the current order of labels around the carousel, read from a fixed point.goal is the target order, read from the same point.start equal goal. Return 0 if they are already equal, and -1 if no number of turns works.Input: start = "abcde", goal = "cdeab"
Output: 2Turning abcde to the left by 2 gives cdeab, which needs 2 turns. Turning to the right by 3 also works, but costs 3. The table tries every number of left turns k from 0 to 4.
| Left turns k | Start after k turns | Equal to the goal? | Turns needed |
|---|---|---|---|
| 0 | abcde | no | - |
| 1 | bcdea | no | - |
| 2 | cdeab | yes | 2 |
| 3 | deabc | no | - |
| 4 | eabcd | no | - |
Input: start = "abcde", goal = "abced"
Output: -1The letters a to e are all there, but abced is not any turn of abcde, because a turn keeps the cyclic order of the labels.
Input: start = "abcabc", goal = "cabcab"
Output: 1Turning abcabc to the left by 2 gives cabcab, and so does turning left by 5. Turning right by 1 is the same as turning left by 5, so the answer is 1.
1 ≤ len(start) ≤ 100,0001 ≤ len(goal) ≤ 100,000a to z.Testing each of up to 100,000 turns label by label costs about 5,000,000,000 comparisons when the labels match for a long time before differing. Each turn of start is a window of start + start, so one linear scan can compare all turns with the goal at once, in about 300,000 steps.