Taro Logo

Couples Holding Hands

Hard
Asked by:
Google
Citadel
Bloomberg LP
Squarepoint Capital
173 views
Topics:
ArraysGreedy Algorithms

There are n couples sitting in 2n seats arranged in a row and want to hold hands.

The people and seats are represented by an integer array row where row[i] is the ID of the person sitting in the ith seat. The couples are numbered in order, the first couple being (0, 1), the second couple being (2, 3), and so on with the last couple being (2n - 2, 2n - 1).

Return the minimum number of swaps so that every couple is sitting side by side. A swap consists of choosing any two people, then they stand up and switch seats.

Example 1:

Input: row = [0,2,1,3]
Output: 1
Explanation: We only need to swap the second (row[1]) and third (row[2]) person.

Example 2:

Input: row = [3,2,0,1]
Output: 0
Explanation: All couples are already seated side by side.

Constraints:

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. How are the couple IDs represented numerically? For example, are couples always formed by adjacent integers like `(0, 1)`, `(2, 3)`, etc., or can they follow a different pairing rule?
  2. Can we assume the input array length `n` is always even and guaranteed to contain a valid, complete set of couples without any missing partners?
  3. What is the expected input range and maximum size of the array, and should we be concerned about integer overflow or memory limits?
  4. Are there any invalid or empty inputs we need to handle, or is the input guaranteed to always be a valid permutation of seated individuals?
  5. If multiple minimum swap sequences can achieve the goal, does it matter which specific swaps are performed as long as the total count is minimized?

Brute Force Solution

Approach

Imagine you have a group of people sitting in a row where partners are separated from each other. The brute force approach involves looking at every possible way to swap people around until every partner is sitting right next to their loved one.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the first person sitting on the far left.
  2. Check if the person sitting right next to them is their proper partner.
  3. If they are already sitting with their partner, leave them alone and move your attention to the next pair of seats.
  4. If they are not partners, look at every single other person remaining in the entire row to see who the correct partner is.
  5. Take that correct partner and physically swap their seat with the person currently sitting next to the lonely individual.
  6. Count this as one swap made.
  7. Repeat this entire process of checking and swapping for every single seat down the line until every partner is holding hands.
  8. Keep track of how many swaps you had to make for this particular attempt, and then imagine undoing everything to try a completely different starting arrangement of swaps to see if you can do it in fewer steps.

Code Implementation

def min_swaps_couples(row_arrangement):
    total_swaps_made = 0
    
    # Iterate through every pair of seats in the row to ensure each couple sits together
    for current_index in range(0, len(row_arrangement), 2):
        expected_person = row_arrangement[current_index]
        
        # Determine the unique identifier for the expected partner based on even-odd pairing rules
        if expected_person % 2 == 0:
            expected_partner = expected_person + 1
        else:
            expected_partner = expected_person - 1
            
        if row_arrangement[current_index + 1] == expected_partner:
            continue
            
        # Search through the remaining seats to locate the correct partner who is separated
        for search_index in range(current_index + 2, len(row_arrangement)):
            if row_arrangement[search_index] == expected_partner:
                row_arrangement[current_index + 1], row_arrangement[search_index] = row_arrangement[search_index], row_arrangement[current_index + 1]
                total_swaps_made += 1
                break
                
    return total_swaps_made

Big(O) Analysis

Time Complexity
O(n²) – To analyze the time complexity, let n represent the total number of people in the row. For each of the n/2 pairs of seats, the algorithm potentially scans the remaining people in the row to find the correct partner. Finding the partner requires checking up to n elements for each pair, and we must perform this search across approximately n/2 pairs. This leads to a total of roughly (n/2) * n operations, which simplifies to the final Big O time complexity of O(n²).
Space Complexity
O(1) – The provided brute force approach uses a few scalar variables to keep track of indices, the current pair being evaluated, and a counter for the number of swaps made. It modifies the original row of people in place by physically swapping seats without allocating any dynamic data structures like hash maps or auxiliary arrays. Because the extra memory required remains constant regardless of the input size, the auxiliary space complexity is strictly O(1).

Optimal Solution

Approach

Instead of trying every possible seating arrangement, we can think of the problem like connecting pairs of people who want to sit together. By looking at who is sitting where and following the chain of partners, we can figure out the minimum number of swaps needed to unite everyone.

Here's how the algorithm would work step-by-step:

  1. Scan through the seats from one end to the other, looking at each pair of adjacent spots.
  2. Check if the two people sitting in the current pair belong together as partners.
  3. If they are already sitting together, leave them alone and move on to the next pair.
  4. If they are not partners, look at one of the people and find out where their actual partner is currently sitting.
  5. Swap that partner into the seat right next to the first person, uniting that couple.
  6. Continue moving down the line, fixing pairs one by one until everyone is sitting next to their partner.
  7. By only making swaps when a pair is broken, you naturally reach the goal in the fewest possible moves.

Code Implementation

def min_swaps_couples(row_of_seats):
    total_swaps_count = 0
    person_to_index_map = {person: index for index, person in enumerate(row_of_seats)}

    # We step by twos because couples occupy pairs of adjacent seats.
    for current_seat_index in range(0, len(row_of_seats), 2):
        first_person = row_of_seats[current_seat_index]
        expected_partner = first_person + 1 if first_person % 2 == 0 else first_person - 1
        second_person_index = current_seat_index + 1

        # If the expected partner is not beside the first person, we must swap.
        if row_of_seats[second_person_index] != expected_partner:
            partner_current_index = person_to_index_map[expected_partner]
            displaced_person = row_of_seats[second_person_index]

            # We update the tracking map to reflect the new positions after swapping.
            row_of_seats[second_person_index], row_of_seats[partner_current_index] = row_of_seats[partner_current_index], row_of_seats[second_person_index]
            person_to_index_map[expected_partner] = second_person_index
            person_to_index_map[displaced_person] = partner_current_index
            total_swaps_count += 1

    return total_swaps_count

Big(O) Analysis

Time Complexity
O(n) – To find the minimum swaps, we iterate through the row of 2n people by jumping two seats at a time, which results in n/2 iterations. Within this loop, checking for partners and locating them takes constant time if we use a position mapping array, or proportional to the array size if we scan for the partner. Assuming a standard linear scan or hash/position lookup, each of the n/2 pairs takes up to O(n) operations in the worst case to find and swap the correct person. This scales as roughly (n/2) * n operations in the naive approach, or simply O(n) if position indices are tracked in constant time. Ultimately, the linear traversal across the n seats dominates the cost, simplifying the total operations to Big O of n.
Space Complexity
O(N) – To efficiently track where each person is currently sitting without repeatedly scanning the array, the optimal solution utilizes a position lookup table or hash map containing N entries, where N represents the total number of people. Additionally, if the algorithm modifies the seat array in place or maintains a tracking structure for visited elements, this auxiliary memory scales linearly with the input size. Therefore, the extra space required beyond the input itself grows directly in proportion to the number of couples N.

Edge Cases

Empty or null input array
How to Handle:
Return zero swaps immediately since no seating arrangements are necessary.
Minimum valid input of length two
How to Handle:
Return zero swaps because a single couple is already seated correctly by definition.
Maximum-sized valid inputs with thousands of elements
How to Handle:
Use an efficient disjoint set union or greedy indexing approach that runs in linear time to avoid timeouts.
Couples already sitting perfectly side-by-side
How to Handle:
Iterate through the array and find zero mismatches, resulting in a total swap count of zero.
Couples in reverse or completely interleaved order
How to Handle:
Form graph cycles where the greedy pointer approach correctly calculates the minimum swaps as size minus number of connected components.
Invalid problem constraints such as odd array lengths
How to Handle:
Assume valid problem constraints where the input length is always even and forms complete pairs.
Disjoint cycles in the swap graph
How to Handle:
Traverse each unvisited node to resolve independent cycles separately without duplicate processing.
Large integer values for couple IDs
How to Handle:
Map IDs to normalized indices using a hash map to handle arbitrarily large or non-sequential identifiers safely.