Skip to content

Commit ee825dc

Browse files
authored
Solved -> 626. Exchange Seats
1 parent eea535a commit ee825dc

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

06_Subqueries/626. Exchange Seats.sql

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
3+
Problem Link -> https://leetcode.com/problems/exchange-seats/description/?envType=study-plan-v2&envId=top-sql-50
4+
5+
------------------------------------------------------------- QUESTION -----------------------------------------------------------
6+
7+
Table: Seat
8+
9+
+-------------+---------+
10+
| Column Name | Type |
11+
+-------------+---------+
12+
| id | int |
13+
| student | varchar |
14+
+-------------+---------+
15+
id is the primary key (unique value) column for this table.
16+
Each row of this table indicates the name and the ID of a student.
17+
id is a continuous increment.
18+
19+
20+
Write a solution to swap the seat id of every two consecutive students. If the number of students is odd, the id of the last student is not swapped.
21+
Return the result table ordered by id in ascending order.
22+
The result format is in the following example.
23+
24+
25+
Example 1:
26+
27+
Input:
28+
Seat table:
29+
+----+---------+
30+
| id | student |
31+
+----+---------+
32+
| 1 | Abbot |
33+
| 2 | Doris |
34+
| 3 | Emerson |
35+
| 4 | Green |
36+
| 5 | Jeames |
37+
+----+---------+
38+
39+
Output:
40+
+----+---------+
41+
| id | student |
42+
+----+---------+
43+
| 1 | Doris |
44+
| 2 | Abbot |
45+
| 3 | Green |
46+
| 4 | Emerson |
47+
| 5 | Jeames |
48+
+----+---------+
49+
50+
Explanation:
51+
Note that if the number of students is odd, there is no need to change the last one's seat.
52+
53+
*/
54+
55+
-- ----------------------------------------------------------- SOLUTION -----------------------------------------------------------
56+
57+
SELECT
58+
CASE
59+
WHEN
60+
id = (SELECT MAX(id) FROM SEAT) AND MOD(id,2) = 1
61+
THEN id
62+
WHEN MOD(id,2) = 1 THEN id + 1
63+
ELSE id - 1
64+
END AS id, student
65+
FROM Seat
66+
ORDER BY id
67+

0 commit comments

Comments
 (0)