first and second. Positions are numbered from zero.
In one operation you may swap any two cards in first; the operation costs i + j, where i and j are the positions of those cards. The second row cannot be touched.
The goal is to have first[i] != second[i] at every position i. Return the smallest total cost of operations that achieves this, or -1 if it is impossible.first=[3, 1, 2], second=[3, 2, 1] → 1
Only position 0 matches. Swapping cards 0 and 1 costs 0 + 1 = 1 and gives [1, 3, 2], where every position differs.
first=[1, 1, 2], second=[1, 1, 3] → -1
Positions 0 and 1 both need a card other than 1, but the first row holds only one such card, the 2. It cannot be done.
first=[1, 2, 3, 4], second=[1, 2, 3, 4] → 6
Every position matches. Swapping 0 and 1 costs 1, swapping 2 and 3 costs 5, for a total of 6.
first.length = second.length = nfirst[i], second[i] ≤ 10⁵first=[3, 1, 2], second=[3, 2, 1]
1
Run checks the first 3 tests in your browser. Submit checks all 119 tests on the server, hidden ones included.