Ctrl K

Fewest Mismatches After Swaps

Medium
Items stand in a row on a shelf: shelf[i] is the code of the item at position i. A layout plan plan of the same length says that position i should hold item plan[i]. You cannot rearrange items freely, only along allowed links: each pair links[k] = [a, b] lets you swap the items at positions a and b. Every link may be used any number of times, in any order. A mismatch is a position i where shelf[i] != plan[i]. Return the smallest number of mismatches you can reach with swaps.
Example 1
shelf=[7, 3, 9, 3], plan=[3, 7, 3, 9], links=[[0, 1], [1, 2]] → 2

Positions 0, 1 and 2 are chained together, so items 7, 3, 9 can be arranged among them freely, e.g. [3, 7, 9, 3]. Positions 0 and 1 match, while position 2 holds 9 instead of 3 and position 3 holds 3 instead of 9. That is 2 mismatches.

Example 2
shelf=[5, 6, 5], plan=[6, 5, 5], links=[] → 2

No swaps are allowed, so positions 0 and 1 stay different.

Example 3
shelf=[4, 8, 2, 6], plan=[6, 2, 8, 4], links=[[0, 3], [2, 1]] → 0

Swap positions 0 and 3, then 1 and 2, and the shelf matches the plan exactly.

Constraints
  • 1 ≤ len(shelf) = len(plan) = n ≤ 10⁵
  • 1 ≤ shelf[i], plan[i] ≤ 10⁵
  • 0 ≤ len(links) ≤ 10⁵
  • links[k] = [a, b], 0 ≤ a, b ≤ n − 1, a ≠ b
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDrain the Landlocked Ponds MediumLand Regions on a Map MediumRatio Chain Queries MediumLargest Forest Patch MediumMerge Contact Cards Medium
loading Python…
Input
shelf=[7, 3, 9, 3], plan=[3, 7, 3, 9], links=[[0, 1], [1, 2]]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 81 tests on the server, hidden ones included.