Couples Holding Hands Problem

Couples Holding Hands Problem — ExecCode Hard DSA Practice

Solve the Couples Holding Hands problem on ExecCode. Free online hard DSA practice in Arrays - Basics. Write and run code in Java, C++, Python — no signup required to run.

Problem description

There are n couples sitting in 2n seats arranged in a row, and they want to hold hands. Person labeled 2i and 2i+1 are a couple for every i. The people are given as row, where row[i] is the label of the person sitting in seat i. Return the minimum number of swaps (each swap exchanges the occupants of any two seats) needed so that every couple ends up sitting side by side.

Examples

Input row = [0, 2, 1, 3]; Output 1. Input row = [3, 2, 0, 1]; Output 0. Input row = [0, 2, 4, 1, 3, 5]; Output 2

Constraints

2n == row.length 2 ≤ n ≤ 30 n is even. 0 ≤ row[i] < 2n All the values of row are unique.

Practice Couples Holding Hands free on ExecCode. Browse DSA problems, topic map, and placement guides.