Table: Seat
+-------------+---------+ | Column Name | Type | +-------------+---------+ | id | int | | student | varchar | +-------------+---------+ 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. The ID sequence always starts from 1 and increments continuously.
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: Seat table: +----+---------+ | id | student | +----+---------+ | 1 | Abbot | | 2 | Doris | | 3 | Emerson | | 4 | Green | | 5 | Jeames | +----+---------+ Output: +----+---------+ | id | student | +----+---------+ | 1 | Doris | | 2 | Abbot | | 3 | Green | | 4 | Emerson | | 5 | Jeames | +----+---------+ Explanation: Note that if the number of students is odd, there is no need to change the last one's seat.
This approach involves iterating through the list and swapping every two consecutive students. The loop runs with a step of 2 to handle even-indexed pairs, ensuring that swaps are done pair-wise. If the total number of students is odd, the last student remains in their original position as there is no pair to swap with.
The C code uses an array of strings to represent students. It swaps the seats by iterating through the array with a step of 2. For each iteration, it swaps the student names using a temporary variable. The last student remains unaltered if the number of students is odd since the iteration breaks before reaching them.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), since each element may be swapped once.
Space Complexity: O(1), as no extra space is used except the temporary variable for swapping.
This method employs a temporary array or list to store swapped results before copying them back to the original list or directly returning them as new results. This makes the logic conceptually simpler at the cost of some additional space usage.
The C variant uses an extra 2D array to initially store swapped pairs, maintaining the original array intact. It later prints the new results by referencing the temporary storage after all swaps are completed.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) due to linear traversal.
Space Complexity: O(n), using a full-sized temporary array.
| Approach | Complexity |
|---|---|
| Approach 1: Direct Swap with Traversal | Time Complexity: O(n), since each element may be swapped once. |
| Approach 2: Use of Temporary Data Structures | Time Complexity: O(n) due to linear traversal. |
LeetCode 626: Exchange Seats [SQL] • Frederik Müller • 10,264 views views
Watch 9 more video solutions →Practice Exchange Seats with our built-in code editor and test cases.
Practice on FleetCode