Trains the technique from
LeetCode 3942Minimum Operations to Sort a PermutationThis is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.
Same function shape, different story and different numbers.
A depot has n bays numbered 0 through n - 1, and nums is a permutation of those numbers giving the pallet parked in each bay.
One exchange swaps the pallets in any two bays. Return the fewest exchanges that put pallet i in bay i for every i.
Example 1
The three bays form a single loop, since bay 0 holds the pallet belonging in bay 2, which holds the one belonging in bay 1, which holds the one belonging in bay 0. Two exchanges settle it.
Example 2
Bay 0 is already right, and the other four bays form two loops of two, each settled by a single exchange.
Example 3
Every pallet is already in its own bay, so no exchange is needed.
The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.
def fewest_exchanges(nums: list[int]) -> int:public int fewestExchanges(int[] nums)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.