Couples Holding Hands

HardGreedyMath

Description

There are n couples sitting in 2n seats arranged in a row. Return the minimum number of swaps so that every couple is sitting side by side.

Examples

Input:row = [0,2,1,3]
Output:1
Explanation:

Swap row[1] and row[2].

Input:row = [3,2,0,1]
Output:0
Explanation:

Couple (2,3) sits in seats 0-1 as [3,2], and couple (0,1) sits in seats 2-3 as [0,1]. Both couples are already adjacent, requiring 0 swaps.

Input:row = [5,4,3,2,1,0]
Output:3
Explanation:

Three swaps are needed to seat each couple side by side.

Constraints

  • 2n == row.length
  • 2 ≤ n ≤ 30
  • 0 ≤ row[i] < 2n

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!