Trains the technique from
LeetCode 1722Minimize Hamming Distance After Swap OperationsThis 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 storage wall has n slots numbered 0 to n - 1. current[i] is the part number sitting in slot i today and wanted[i] is the part number the new layout asks for in slot i.
The wall's rails only let certain slots exchange contents. swaps lists those rails: swaps[k] = [a, b] means the contents of slot a and slot b may be exchanged, and a rail may be used as many times as you like, in any order, including rails that share a slot. Rails may be listed more than once.
A slot is wrong when the part number it holds is not the part number the new layout asks for in that slot. Perform any number of exchanges along the rails and return the smallest number of wrong slots you can end up with.
Example 1
Exchange slots 1 and 2 to reach `[1, 3, 2]`, then slots 0 and 1 to reach `[3, 1, 2]`, then slots 1 and 2 again to reach `[3, 2, 1]`. Every slot now holds the part number the new layout asks for.
Example 2
Exchanging slots 0 and 1 gives `[9, 7, 8, 10]`, so slot 1 is right. Exchanging slots 2 and 3 gives `[9, 7, 10, 8]`, so slot 2 is right as well. Slots 0 and 3 are still wrong, which is two wrong slots.
Example 3
The two rails let the three part numbers 4, 4 and 6 be arranged across the three slots in any order. Leaving them where they are makes slots 0 and 1 right, with slot 2 holding 6 while the layout asks for 9, which is one wrong slot.
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_wrong_slots(current: list[int], wanted: list[int], swaps: list[list[int]]) -> int:public int fewestWrongSlots(int[] current, int[] wanted, int[][] swaps)See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.