Problem 626

Abstract / Summary

Given a grid of seats marked as taken or empty, move people to seats in the same row or column if possible so that as many people as possible sit next to each other.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
7 lines | 244 bytes | submitted September 6, 2023 | GitHub  

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 75% (600k+ submissions).

Typical patterns to solve this problem:
  • Database
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.08 | σ = 0.92

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
14 links | 7 authors | 5 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

26 easy 21 medium 5 hard
53 solutions   September 6, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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