The Exchange Seats coding problem is a SQL task where you are given a table Seat with two columns: id and student. You need to swap the seats of every two adjacent students. If the total number of students is odd, the last student's seat remains unchanged. The output should be ordered by ID.
Companies like Zomato and Amazon use this Database interview pattern to test your ability to use conditional logic and arithmetic in SQL. It evaluates if you can manipulate row indices using CASE statements and modular math. It’s a practical test of how you handle data transformations that depend on neighboring records.
This is a Conditional Update/Select problem in SQL.
CASE statement to adjust the id for each row:
id is odd and it's not the last row: new id = id + 1.id is even: new id = id - 1.id is odd and it is the last row: id remains the same.id.id.Seats: (1, Abbot), (2, Bob), (3, Chris), (4, Doris), (5, Emerson)
(1, Bob), (2, Abbot), (3, Doris), (4, Chris), (5, Emerson).CASE statement on the ID is much more readable and efficient.ORDER BY id clause at the end.In SQL, you can get the total count of rows using a subquery: (SELECT COUNT(*) FROM Seat). Use this inside your CASE statement to check if the current odd ID is the last one.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Confirmation Rate | Medium | Solve | |
| Product Sales Analysis III | Medium | Solve | |
| Rank Scores | Medium | Solve | |
| Monthly Transactions I | Medium | Solve | |
| Product Price at a Given Date | Medium | Solve |