LeetCode 626: Exchange Seats [SQL]
ฝัง
- เผยแพร่เมื่อ 14 ต.ค. 2024
- Solution and walkthrough of leetcode database problem 626: Exchange Seats. I'm using MySQL but this solution should work in any SQL dialect such as PostgreSQL SQL Server, etc.
Link to the problem: leetcode.com/p...
Thanks alot for your explanation. I would say using window function can be more efficient here, here is an example:
select id,
case when id%2=1 then lead(student,1,student) over (order by id)
else lag(student) over(order by id)
End as student
from Seat
thank you sir .. for your answer it really meaningful and understandable
Very good solution, thank you!!
I like how you solve all the problems with basic logic instead of using fancy terminologies. As programmers , we should stick to logic instead of using fancy built in functions.
yes, the goal is to make everyone understand and not use fancy terminology and functions just for the sake of using them.
You explained so well bro. A lot of questions I was so confused looking at the answer. You are so good!!!
I solved this query by using windows function
create TABLE seat
(
id int not null primary key,
name VARCHAR(20)
);
insert into seat VALUES(1,'Raman'),(2,'Sanjiv'),(3,'Saloni'),(4,'Shweta'),(5,'Mohit');
select * from seat;
select *,
case when id%2 != 0 then lead(name,1,name) over(ORDER by id)
when id%2 = 0 then lag(name) over(ORDER by id)
else name END as exchange_seat_student_name
from seat;
MS SQL:
select id, case when mod(id,2)=0 then lag(student) over (order by id)
when lead(student) over (order by id) IS NULL then student
else lead(student) over (order by id)
end as student
from seat order by id
Smart move, as I was struggling with exchanging names.
You explain very well. Your explanations are clear.
Clear, simple explanation!
Another logic approach is to get the previous and next student name and decide which to display, it is much cleaner and easier to understand solution::
SELECT id,
CASE
WHEN id % 2 = 0 THEN LAG(student, 1) OVER() #even show previous
WHEN id % 1 = 0 AND LEAD(student, 1) OVER() IS NOT NULL THEN LEAD(student, 1) OVER() #odd show next
ELSE student #last record/row
END as student
FROM Seat
what is the use of id%1=0
you explained it so well.
Smart, thank you.
good one
Lengendary