All problems
0866MediumArray

Fewest Exchanges to Order the Bays

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3942Minimum Operations to Sort a Permutation

This 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.

Examples

Example 1

Input
nums = [2, 0, 1]
Output
2

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

Input
nums = [0, 2, 1, 4, 3]
Output
2

Bay 0 is already right, and the other four bays form two loops of two, each settled by a single exchange.

Example 3

Input
nums = [0, 1, 2, 3]
Output
0

Every pallet is already in its own bay, so no exchange is needed.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 99999
  • nums is a permutation of the numbers from 0 to nums.length - 1

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_exchanges(nums: list[int]) -> int:
Java
public int fewestExchanges(int[] nums)
September 7
Apply