Problem
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.
Examples
Example 1:
Input: Seat table:
|
|
Output:
|
|
Explanation: Note that if the number of students is odd, there is no need to change the last one’s seat.
Solution
Method 1 - Select with case
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
- The main complexity arises from the subquery
(SELECT MAX(id) FROM Seat)
which isO(1)
as it aggregates a single value. - Thus, the overall complexity for the query is
O(n)
, wheren
is the number of rows in theSeat
table given that it scans all rows once.
- The main complexity arises from the subquery
- 🧺 Space complexity:
O(1)
- The space complexity is
O(1)
for the additional storage needed during query execution since we’re not using any extra space that’s dependent on input size aside from the result set.
- The space complexity is