#626

Exchange Seats

Medium
DatabaseArrayIn-place swapping
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(1)
💡

Intuition

Time O(n)Space O(1)

In the optimal solution, we can directly swap the IDs in a single pass through the list. This avoids the overhead of creating a new list and sorting it, making it more efficient.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through the list of students in steps of 2.
  2. 2Step 2: For each pair, swap their IDs directly in the original list.
  3. 3Step 3: Return the modified list, which is already in the correct order.
solution.py4 lines
1def exchangeSeats(seats):
2    for i in range(0, len(seats) - 1, 2):
3        seats[i], seats[i + 1] = seats[i + 1], seats[i]  # Swap
4    return seats

Complexity note: The time complexity is O(n) because we only make a single pass through the list. The space complexity is O(1) since we are swapping in place without using additional data structures.

  • 1Swapping pairs can be done in a single pass for efficiency.
  • 2Understanding how to manipulate lists directly can save time and space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.