Exchange Seats
Medium
SQLCASEMath
Problem
Schema: Seat(id INT, student VARCHAR) where id is sequential 1..N.
Swap each pair of adjacent students: (1,2) swap, (3,4) swap, ... If N is odd, the last row stays put. Return the new (id, student) listing.
Example 1
Input: (1,A) (2,B) (3,C) (4,D) (5,E)
Output: (1,B) (2,A) (3,D) (4,C) (5,E)
Constraints
- 1 ≤ N ≤ 10⁵.
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
SQL
SELECT
CASE
WHEN id % 2 = 1 AND id = (SELECT MAX(id) FROM Seat) THEN id
WHEN id % 2 = 1 THEN id + 1
ELSE id - 1
END AS id,
student
FROM Seat
ORDER BY id;
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Exchange Seats interactively → ← All solutions