Parcel-delivery app~20 min2s · 256 MBtarget O(n) time, O(n) spacesorting
A parcel hub has a belt with n slots, numbered 0 to n − 1. Each slot holds one parcel. The parcel in slot i must end up in slot slots[i], and every slot is the target of exactly one parcel.
A worker can swap the parcels in any two slots, and each swap takes a minute. The hub wants the belt in order as soon as possible.
Find the fewest swaps that put every parcel in its target slot.
Write fewest_swaps(slots).
slots[i] is the target slot of the parcel now in slot i.slots are each of the numbers 0 to n − 1 exactly once.Input: slots = [2, 0, 1, 4, 3]
Output: 3Follow each parcel to its target. The parcel in slot 0 goes to slot 2, the one in slot 2 goes to slot 1, and the one in slot 1 goes to slot 0. That is a cycle of 3 slots. Slots 3 and 4 swap their parcels, a cycle of 2.
| Cycle | Slots | Swaps needed |
|---|---|---|
| 1 | 0, 2, 1 | 2 |
| 2 | 3, 4 | 1 |
A cycle of m slots needs m − 1 swaps, so the answer is 3.
Input: slots = [0, 1, 2]
Output: 0Every parcel is already in its target slot.
Input: slots = [3, 2, 1, 0]
Output: 2Slots 0 and 3 swap their parcels, and slots 1 and 2 swap theirs: two cycles of 2.
0 ≤ slots.length ≤ 100,000 (belt slots)0 ≤ slots[i] ≤ 99,999, and each of the numbers 0 to n − 1 appears exactly onceFinding the right parcel for each slot by scanning the rest of the belt costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. Following each parcel to its target once costs n steps in all.