Maps app~22 min2s · 256 MBtarget O(n) time, O(n) spacegreedy
You work on a parking and navigation app that guides valets in a garage with n bays in a row. Bay i is meant for the car with number i, counting from 0. Number 0 is not a car: it stands for the empty bay.
A valet can only move one car per step, into the empty bay. That swaps the empty bay with one car. Your team lead asks: "What is the fewest moves that put every car, and the empty bay, in its own place?" The garage can have 100,000 bays.
Write fewest_moves(bays).
bays[i] is the number of the car in bay i, with 0 for the empty bay. The values are the numbers 0 to n - 1, each once.bays[i] = i for every bay.0 when every car is already in place.Input: bays = [3, 0, 2, 1, 5, 4, 6]
Output: 5Follow the cars: bay i holds car bays[i], which belongs in bay bays[i]. The bays fall into cycles, and each cycle can be fixed on its own.
| Cycle of bays | Length | Holds the empty bay | Moves |
|---|---|---|---|
| [0, 3, 1] | 3 | yes | 2 |
| [2] | 1 | no | 0 (already in place) |
| [4, 5] | 2 | no | 3 |
| [6] | 1 | no | 0 (already in place) |
The moves add up to 5.
Input: bays = [0, 1, 2, 3]
Output: 0Every car is in its own bay, so no move is needed.
Input: bays = [1, 0, 2]
Output: 1The empty bay and car 1 have swapped places. One move swaps them back.
1 ≤ len(bays) ≤ 100,000bays holds each number from 0 to len(bays) - 1 exactly onceSearching every arrangement of the cars is n factorial states, which is hopeless beyond about 10 bays. Even a search that tries each swap at each step grows too fast. The bays fall into separate cycles that can be handled independently, and a single pass over them takes about 100,000 steps.