Couples Holding Hands

HardGreedygreedy

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

There are n couples sitting in 2n seats in a row, described by row, where row[i] is the person in seat i. People are numbered 0 to 2n - 1, and the couples are (0, 1), (2, 3), ..., (2n - 2, 2n - 1). A swap exchanges the people in any two seats. Return the minimum number of swaps needed so that every couple sits side by side in one of the seat pairs (0, 1), (2, 3), and so on. Aim for O(n) time.

Examples

Input: row = [0,2,1,3]
Output: 1
Swapping the people in seats 1 and 2 gives [0,1,2,3].
Input: row = [3,2,0,1]
Output: 0
Both couples are already seated together.

Constraints

  • 2n == row.length
  • 2 <= row.length <= 60
  • `row` is a permutation of `0..2n-1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More greedy problems