Exchange Seats LeetCode Solution

Last updated on October 9th, 2024 at 10:00 pm

This Leetcode problem Exchange Seats LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Medium

Exchange Seats LeetCode Solution

Exchange Seats LeetCode Solution

Problem Statement

Column NameType
idint
studentvarchar
Table: Seat

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. id is a continuous increment.

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.

The result format is in the following example.

Example 1:
Input:

idstudent
1Abbot
2Doris
3Emerson
4Green
5Jeames
Seat table:

Output:

idstudent
1Doris
2Abbot
3Green
4Emerson
5Jeames

Explanation: Note that if the number of students is odd, there is no need to change the last one’s seat.

1. Exchange Seats LeetCode Solution MySQL

select 
  if(
    mod(id, 2) = 0, 
    id - 1, 
    if(
      id < (
        select 
          max(id) 
        from 
          seat
      ), 
      id + 1, 
      id
    )
  ) as id, 
  student 
from 
  seat 
order by 
  id;
Scroll to Top