Exchange Seats — LeetCode 626 Python Solution

MediumDatabase
Problem
#626
Reading time
3 min

The problem

Swap the seats of every pair of neighbouring students, so seat 1 trades with seat 2, seat 3 with seat 4, and so on. When the number of students is odd the last one keeps their seat. Report the new seating ordered by id. The Seat table has one row per student: id (int, the primary key) and student (varchar). The ids start at 1 and increase without gaps.

Example

Seat table:

| id | student |
| -- | ------- |
| 1  | Nadia   |
| 2  | Oscar   |
| 3  | Petra   |
| 4  | Rui     |
| 5  | Tomas   |

Result:

| id | student |
| -- | ------- |
| 1  | Oscar   |
| 2  | Nadia   |
| 3  | Rui     |
| 4  | Petra   |
| 5  | Tomas   |

The first two students trade seats and so do the next two, while Tomas is the odd one out at the last seat and stays where he is.

Python solution

Python
import pandas as pd

def exchange_seats(seat: pd.DataFrame) -> pd.DataFrame:
    df = seat.copy()
    max_id = df['id'].max()
    def swap_id(x):
        if x % 2 == 1 and x != max_id:
            return x + 1
        if x % 2 == 0:
            return x - 1
        return x
    df['new_id'] = df['id'].apply(swap_id)
    res = df.sort_values('new_id').rename(columns={'new_id': 'id'})
    return res[['id', 'student']]

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 626. Exchange Seats?
LeetCode 626. Exchange Seats is rated Medium on LeetCode.
What topics does LeetCode 626. Exchange Seats cover?
LeetCode 626. Exchange Seats is tagged Database on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview