Skip to content

Commit 0c0ef59

Browse files
Ibrahim Added Exchange Seats
1 parent 58f36ee commit 0c0ef59

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# [Exchange Seats](https://leetcode.com/problems/exchange-seats/description/?envType=study-plan-v2&envId=top-sql-50)
2+
3+
### Problem Requirements:
4+
5+
Write a query to swap the seat <code>id</code> of every two consecutive students. If the number of students is <strong>odd</strong>, the <code>id</code> of the last student is <strong>not</strong> swapped.
6+
7+
Return the result table ordered by <code>id</code> in <strong>ascending order</strong>.
8+
9+
<details>
10+
<summary style="font-size:1.3rem;"> <strong>Hints</strong> </summary>
11+
12+
<details>
13+
<summary>Hint#1</summary>
14+
<p>How to determine if a student should be swapped or not?</p>
15+
</details>
16+
17+
<details>
18+
<summary>Hint#2</summary>
19+
<p>A student will be swapped if and only if he is not the last student or the number of students is even.</p>
20+
</details>
21+
22+
<details>
23+
<summary>Hint#3</summary>
24+
<p>Suppose that a student will be swapped. What is the id of the student he or will be swapped with?</p>
25+
</details>
26+
27+
<details>
28+
<summary>Hint#4</summary>
29+
<p>If a student is going to be swapped, he will be swapped with the student having his id plus one or minus one depending on the parity of the student's id.</p>
30+
</details>
31+
32+
</details>
33+
34+
<details>
35+
<summary style="font-size:1.3rem;"> <strong>Explanation</strong> </summary>
36+
37+
We will use a subquery to get the student's name after swapping. We will change the student's name if he isn't the last student or the number of students is even.
38+
39+
To swap the student's name, we will check the parity of the student id. If the student id is odd he will be given the name of the student having his id plus one. Otherwise, he will be given the name of the student having his id minus one.
40+
41+
</details>
42+
43+
<details>
44+
<summary style="font-size:1.3rem"><strong> SQL Solution</strong> </summary>
45+
46+
```sql
47+
SELECT s.id AS id,
48+
IF(
49+
s.id < (SELECT count(*) FROM Seat)
50+
OR
51+
MOD((SELECT count(*) FROM Seat), 2) = 0
52+
,
53+
(
54+
SELECT student
55+
FROM Seat
56+
WHERE id = IF(MOD(s.id, 2) = 1, s.id+1, s.id-1)
57+
)
58+
,
59+
s.student
60+
) as student
61+
FROM Seat as s
62+
ORDER BY id;
63+
```
64+
65+
</details>

0 commit comments

Comments
 (0)