FunctionRacerProblemsRace

Seat the Pairs Together

HardGreedyPython, JavaScript, TypeScript, Java, C++

An even number of people sit in a row of seats, and row[i] is the person in seat i. The people are numbered from 0, and they came in pairs: 0 with 1, 2 with 3, 4 with 5 and so on.

The seats are double seats: seats 0 and 1 belong together, then seats 2 and 3, and so on. One swap lets any two people trade places.

Return the fewest swaps after which every pair shares a double seat.

Example 1

row [3,0,1,2]
returns 1

Person 3 sits with 0. Trading 0 and 2 puts 3 next to 2, and 1 next to 0.

Example 2

row [0,1,3,2]
returns 0

Both pairs already share a double seat. The order inside a seat does not matter.

Example 3

row [0,2,4,1,3,5]
returns 2

Each double seat holds people from two different pairs, and the three pairs form one ring. The first swap completes one pair, the second completes the other two.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Greedy problems