From a4c8f3fc8df5a6b80b2d83fb19873ff32d6c1142 Mon Sep 17 00:00:00 2001 From: ivanbyone Date: Tue, 8 Jul 2025 11:05:54 +0300 Subject: [PATCH] task: #626 --- README.md | 1 + leetcode/medium/626. Exchange Seats.sql | 43 +++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 leetcode/medium/626. Exchange Seats.sql diff --git a/README.md b/README.md index bbb9992..74db791 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ Have a good contributing! - [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql) - [570. Managers with at Least 5 Direct Reports](./leetcode/medium/570.%20Managers%20with%20at%20Least%205%20Direct%20Reports.sql) - [602. Friend Requests II: Who Has the Most Friends](./leetcode/medium/602.%20Friend%20Requests%20II:%20Who%20Has%20the%20Most%20Friends.sql) + - [626. Exchange Seats](./leetcode/medium/626.%20Exchange%20Seats.sql) - [1045. Customers Who Bought All Products](./leetcode/medium/1045.%20Customers%20Who%20Bought%20All%20Products.sql) - [1070. Product Sales Analysis III](./leetcode/medium/1070.%20Product%20Sales%20Analysis%203.sql) - [1158. Market Analysis 1](./leetcode/medium/1158.%20Market%20Analysis%201.sql) diff --git a/leetcode/medium/626. Exchange Seats.sql b/leetcode/medium/626. Exchange Seats.sql new file mode 100644 index 0000000..5a724e1 --- /dev/null +++ b/leetcode/medium/626. Exchange Seats.sql @@ -0,0 +1,43 @@ +/* +Question 626. Exchange Seats +Link: https://leetcode.com/problems/exchange-seats/description/?envType=study-plan-v2&envId=top-sql-50 + +Table: Seat + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| id | int | +| student | varchar | ++-------------+---------+ +id is the primary key (unique value) column for this table. +Each row of this table indicates the name and the ID of a student. +The ID sequence always starts from 1 and increments continuously. + + +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. + +Return the result table ordered by id in ascending order. +*/ + +SELECT + s.id, + (CASE + WHEN s.id % 2 = 0 THEN s1.student + WHEN s3.student IS NULL THEN s.student + WHEN s.id % 2 = 1 THEN s3.student + END) AS student +FROM Seat AS s +LEFT JOIN + Seat AS s1 + ON s.id = ( + SELECT MIN(s2.id) FROM Seat AS s2 + WHERE s1.id < s2.id + ) +LEFT JOIN + Seat AS s3 + ON s.id = ( + SELECT MAX(s4.id) FROM Seat AS s4 + WHERE s3.id > s4.id + ) + \ No newline at end of file