Ctrl K

Pull Matching Cards Apart

Hard
Two rows of numbered cards of the same length n lie on the table: 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.
Example 1
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.

Example 2
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.

Example 3
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.

Constraints
  • 1 ≤ n ≤ 10⁵
  • first.length = second.length = n
  • 1 ≤ first[i], second[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsJobs With a Cooldown MediumSpread Out the Labels MediumPick Within Tag Limits MediumFewest Kinds After Removals MediumBalance the Dice Rows Medium
loading Python…
Input
first=[3, 1, 2], second=[3, 2, 1]
Expected
1

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