MySQL 0626.sql
SELECT CASE WHEN id % 2 = 0 THEN id - 1
WHEN id = (SELECT MAX(id) FROM Seat) THEN id
ELSE id + 1
END AS id,
student
FROM Seat
ORDER BY id
Difficulty
and has an acceptance rate of about 75% (600k+ submissions).
Typical patterns to solve this problem:
- Database
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided query transforms the id column of the Seat table while preserving the associated student value. It applies a conditional adjustment to each row: even identifiers are decremented, the highest identifier remains unchanged, and all other identifiers are incremented. The result set is then ordered by the newly calculated identifier, delivering a deterministic sequence that reflects the applied rules.
Key Steps
The transformation is driven by a CASE expression that evaluates three distinct conditions. The first condition checks whether the original id is an even number. When true, the expression subtracts one from the id. The second condition identifies the row that holds the maximum id value in the entire table; this row is left untouched. The final ELSE clause captures all remaining rows, incrementing their id by one. The expression is aliased as id to replace the original column in the output.
SELECT CASE
WHEN id % 2 = 0 THEN id - 1
WHEN id = (SELECT MAX(id) FROM Seat) THEN id
ELSE id + 1
END AS id,
student
FROM Seat
ORDER BY id;
The ORDER BY clause uses the computed id alias, ensuring that the rows are presented in the order dictated by the transformed identifiers rather than the original ordering.
Edge Cases Handled
When an identifier is even, the subtraction of one guarantees that the resulting value becomes odd, preventing any collision with other even identifiers that might also be decremented. The query explicitly isolates the row with the maximum identifier; this prevents the maximum value from being altered, which could otherwise cause it to exceed the logical range of identifiers after the increment operation. For identifiers that are odd and not the maximum, the increment operation moves them to the next even number, preserving a clear separation between the three categories of rows.
Performance Optimizations
The use of a single SELECT statement with an inline CASE expression avoids the need for multiple passes over the data or temporary tables. The subquery (SELECT MAX(id) FROM Seat) can be efficiently resolved by the database engine using an index on the id column, if one exists, allowing the maximum value to be retrieved with minimal I/O. By computing the transformed identifier directly in the projection list, the query eliminates the overhead of additional columns or intermediate calculations. Finally, ordering by the derived id leverages the fact that the expression yields a simple arithmetic result, enabling the optimizer to apply a straightforward sort operation without complex expression evaluation during the sort phase.
ELI5 - Simplified Explanation
Imagine a classroom full of students sitting in chairs that are lined up in a row. Each student has a special number taped to the back of their chair. The teacher wants to have a fun switch-up where the students swap seats with their neighbors. The computer looks at the number on each chair to decide who moves where. If the chair number can be split exactly into two even groups, the student moves to the chair right before them. If the chair number is the very last one in the whole long row, the student gets to stay exactly where they are. For everyone else, the student moves to the chair right after them. After all the moving is finished, the teacher puts the rows back in order from the smallest number to the largest number so everything stays neat and tidy.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++ | Java | Python | |||
| Progiez | C++ | Java | Python | |||
| github | everthis | SQL | ||||
| suxrobGM | SQL | |||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| LeetcodeHelp | C++, Java, Python | |||||
| Progiez | C++, Java, Python | |||||
| everthis | SQL | |||||
| suxrobGM | SQL |
Videos
Similar Problems
Solved On The Same Day
- problem 175: Combine Two Tables
- problem 181: Employees Earning More Than Their Managers
- problem 182: Duplicate Emails
- problem 183: Customers Who Never Order
- problem 193: Valid Phone Numbers
- problem 196: Delete Duplicate Emails
- problem 197: Rising Temperature
- problem 203: Remove Linked List Elements
- problem 511: Game Play Analysis I
- problem 577: Employee Bonus
- problem 584: Find Customer Referee
- problem 586: Customer Placing the Largest Number of Orders
- problem 595: Big Countries
- problem 596: Classes With at Least 5 Students
- problem 607: Sales Person
- problem 610: Triangle Judgement
- problem 619: Biggest Single Number
- problem 620: Not Boring Movies
- problem 627: Swap Sex of Employees
- problem 1050: Actors and Directors Who Cooperated At Least Three Times
- problem 1068: Product Sales Analysis I
- problem 1075: Project Employees I
- problem 1084: Sales Analysis III
- problem 1141: User Activity for the Past 30 Days I
- problem 1148: Article Views I
- problem 1179: Reformat Department Table
- problem 176: Second Highest Salary
- problem 177: Nth Highest Salary
- problem 178: Rank Scores
- problem 180: Consecutive Numbers
- problem 184: Department Highest Salary
- problem 192: Word Frequency
- problem 194: Transpose File
- problem 550: Game Play Analysis IV
- problem 570: Managers with at Least 5 Direct Reports
- problem 585: Investments in 2016
- problem 602: Friend Requests II: Who Has the Most Friends
- problem 608: Tree Node
- problem 725: Split Linked List in Parts
- problem 1045: Customers Who Bought All Products
- problem 1070: Product Sales Analysis III
- problem 1164: Product Price at a Given Date
- problem 1174: Immediate Food Delivery II
- problem 1193: Monthly Transactions I
- problem 1204: Last Person to Fit in the Bus
- problem 1321: Restaurant Growth
- problem 1393: Capital Gain/Loss
- problem 174: Dungeon Game
- problem 185: Department Top Three Salaries
- problem 218: The Skyline Problem
- problem 262: Trips and Users
- problem 601: Human Traffic of Stadium
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality