Talentd
FleetCode
Make and follow sheets.Sign in

Exchange Seats solution and explanation

MediumDatabase5 min read75.1% acceptanceUpdated 9 Apr 2026
Exchange Seats | Leetcode 626 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 8:08 · 12K viewsWatch on YouTube
9 more videos on this problem
  1. Exchange Seats | Leetcode 626 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 8:08 · 12K views
  2. LeetCode 626: Exchange Seats [SQL]Frederik Müller · 7:58 · 11K views
  3. LeetCode Medium 626 Amazon Interview SQL Question with Detailed ExplanationEveryday Data Science · 8:38 · 8K views
  4. LeetCode Medium 626.Exchange Seats Solution with Detailed Explanation - MySQL and MS SQL ServerCode With Katia · 6:08 · 1K views
  5. LeetCode - 626. Exchange Seats (SQL)Chain Of Thought · 4:10 · 631 views
  6. 626. Exchange Seats - LeetCode SQL Solution [MEDIUM]Code with Carter · 6:16 · 597 views
  7. LeetCode in MySQL 626. Exchange Seats - Michelle小梦想家 (English Version)Michelle小梦想家 · 10:04 · 443 views
  8. Exchange Seats (Leetcode 626) in Telugu [ASMR]Coding Interview Preparation · 5:51 · 113 views
  9. 626. Exchange Seats | LeetCode | SQL | Solution | Interview ProblemData Alchemist · 7:31 · 104 views
  10. Crack SQL Challenges: Swapping Seats in a Breeze | LeetCode Problem 626 SolvedvanAmsen · 4:14 · 86 views

The problem

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.

Approach overview

Problem Overview: The table stores students with sequential seat IDs. The task is to swap every pair of adjacent seats: seat 1 with seat 2, seat 3 with seat 4, and so on. If the number of rows is odd, the final seat remains unchanged.

Approach 1: Direct Swap with Traversal (Time: O(n), Space: O(1))

This approach iterates through the rows in seat order and swaps adjacent pairs as it goes. When the current seat index is odd, exchange it with the next seat. When the index is even, it has already been handled by the previous step. In SQL-style logic, this is often implemented with a CASE expression that increments or decrements the seat ID depending on whether the row index is odd or even, while checking if a next row exists. The algorithm performs a single pass over the dataset, making it efficient and easy to reason about. This technique is essentially a simulation of pairwise swapping and works well when rows are already ordered by ID.

Approach 2: Use of Temporary Data Structures (Time: O(n), Space: O(n))

This method first copies the seat data into a temporary structure such as an array or intermediate table. Iterate through the collection in steps of two and swap elements at positions i and i + 1. If the total number of elements is odd, the final element remains untouched. After processing, rebuild the result set using the updated order. The approach is straightforward and useful when you want clearer manipulation logic or when transformations are easier to express outside a direct query. The tradeoff is extra memory usage because all rows must be stored before swapping.

In database environments, the same idea is commonly expressed with SQL constructs like CASE, COUNT(), or window functions to determine whether a seat should move forward or backward. The key insight is that swapping happens strictly in adjacent pairs, so each row only needs to look at its immediate neighbor.

Recommended for interviews: The direct traversal or SQL CASE approach is what interviewers typically expect. It demonstrates that you recognize the pairwise pattern and can implement the swap in a single pass with constant extra space. Showing the temporary structure approach first can help explain the idea clearly, but the in-place or query-based swap highlights stronger optimization instincts.

Approach 1: Approach 1: Direct Swap with Traversal

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.

def swap_seats(students):
    for i in range(0, len(students) - 1, 2):
        students[i], students[i + 1] = students[i + 1], students[i]
    return students

students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"]
result = swap_seats(students)
for i, student in enumerate(result, 1):
    print(i, student)
import java.util.ArrayList;
import java.util.List;

public class SeatSwap {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>();
        students.add("Abbot");
        students.add("Doris");
        students.add("Emerson");
        students.add("Green");
        students.add("Jeames");

        swapSeats(students);

        for (int i = 0; i < students.size(); i++) {
            System.out.println((i + 1) + " " + students.get(i));
        }
    }

    static void swapSeats(List<String> students) {
        for (int i = 0; i < students.size() - 1; i += 2) {
            String temp = students.get(i);
            students.set(i, students.get(i + 1));
            students.set(i + 1, temp);
        }
    }
}
#include <iostream>
#include <vector>
#include <string>

void swapSeats(std::vector<std::string> &students) {
    for (size_t i = 0; i < students.size() - 1; i += 2) {
        std::swap(students[i], students[i + 1]);
    }
}

int main() {
    std::vector<std::string> students = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
    swapSeats(students);
    for (size_t i = 0; i < students.size(); ++i) {
        std::cout << i + 1 << " " << students[i] << std::endl;
    }
    return 0;
}
function swapSeats(students) {
    for (let i = 0; i < students.length - 1; i += 2) {
        [students[i], students[i + 1]] = [students[i + 1], students[i]];
    }
    return students;
}

let students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"];
let result = swapSeats(students);
result.forEach((student, index) => console.log(index + 1, student));
#include <stdio.h>

void swapSeats(char students[][20], int n) {
    for (int i = 0; i < n - 1; i += 2) {
        char temp[20];
        strcpy(temp, students[i]);
        strcpy(students[i], students[i + 1]);
        strcpy(students[i + 1], temp);
    }
}

int main() {
    char students[][20] = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
    int n = 5;
    
    swapSeats(students, n);
    
    for (int i = 0; i < n; i++) {
        printf("%d %s\n", i + 1, students[i]);
    }
    return 0;
}
using System;
using System.Collections.Generic;

class Program
{
    static void SwapSeats(List<string> students)
    {
        for (int i = 0; i < students.Count - 1; i += 2)
        {
            string temp = students[i];
            students[i] = students[i + 1];
            students[i + 1] = temp;
        }
    }

    static void Main()
    {
        List<string> students = new List<string> { "Abbot", "Doris", "Emerson", "Green", "Jeames" };
        SwapSeats(students);
        for (int i = 0; i < students.Count; i++)
        {
            Console.WriteLine((i + 1) + " " + students[i]);
        }
    }
}

In Python, lists (which are mutable) are utilized to store students’ names. The swap occurs using tuple unpacking, a simple way to efficiently exchange the two elements at adjacent positions.

Complexity

Time Complexity: O(n), where n is the number of students.
Space Complexity: O(1), due to in-place operations.

Try this approach in the editor

Approach 2: Approach 2: Use of Temporary Data Structures

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.

def swap_seats_using_temp(students):
    result = students[:]
    for i in range(0, len(students) - 1, 2):
        result[i], result[i + 1] = students[i + 1], students[i]
    return result

students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"]
result = swap_seats_using_temp(students)
for i, student in enumerate(result, 1):
    print(i, student)
import java.util.ArrayList;
import java.util.List;

public class SeatSwapTempList {
    public static void main(String[] args) {
        List<String> students = new ArrayList<>();
        students.add("Abbot");
        students.add("Doris");
        students.add("Emerson");
        students.add("Green");
        students.add("Jeames");

        List<String> result = swapSeats(students);

        for (int i = 0; i < result.size(); i++) {
            System.out.println((i + 1) + " " + result.get(i));
        }
    }

    static List<String> swapSeats(List<String> students) {
        List<String> result = new ArrayList<>(students);
        for (int i = 0; i < students.size() - 1; i += 2) {
            String temp = result.get(i);
            result.set(i, result.get(i + 1));
            result.set(i + 1, temp);
        }
        return result;
    }
}
#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> swapSeatsUsingTemp(const std::vector<std::string> &students) {
    std::vector<std::string> result = students;
    for (size_t i = 0; i < students.size() - 1; i += 2) {
        std::swap(result[i], result[i + 1]);
    }
    return result;
}

int main() {
    std::vector<std::string> students = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
    std::vector<std::string> result = swapSeatsUsingTemp(students);
    for (size_t i = 0; i < result.size(); ++i) {
        std::cout << i + 1 << " " << result[i] << std::endl;
    }
    return 0;
}
function swapSeatsUsingTemp(students) {
    let result = [...students];
    for (let i = 0; i < students.length - 1; i += 2) {
        [result[i], result[i + 1]] = [students[i + 1], students[i]];
    }
    return result;
}

let students = ["Abbot", "Doris", "Emerson", "Green", "Jeames"];
let result = swapSeatsUsingTemp(students);
result.forEach((student, index) => console.log(index + 1, student));
#include <stdio.h>
#include <string.h>

void swapSeatsUsingTemp(char students[][20], int n) {
    char result[n][20];
    for (int i = 0; i < n - 1; i += 2) {
        strcpy(result[i], students[i + 1]);
        strcpy(result[i + 1], students[i]);
    }
    if (n % 2 != 0) {
        strcpy(result[n - 1], students[n - 1]);
    }
    for (int i = 0; i < n; i++) {
        printf("%d %s\n", i + 1, result[i]);
    }
}

int main() {
    char students[][20] = {"Abbot", "Doris", "Emerson", "Green", "Jeames"};
    int n = 5;
    swapSeatsUsingTemp(students, n);
    return 0;
}
using System;
using System.Collections.Generic;

class Program
{
    static List<string> SwapSeatsUsingTemp(List<string> students)
    {
        List<string> result = new List<string>(students);
        for (int i = 0; i < students.Count - 1; i += 2)
        {
            string temp = result[i];
            result[i] = result[i + 1];
            result[i + 1] = temp;
        }
        return result;
    }

    static void Main()
    {
        List<string> students = new List<string> { "Abbot", "Doris", "Emerson", "Green", "Jeames" };
        List<string> result = SwapSeatsUsingTemp(students);
        for (int i = 0; i < result.Count; i++)
        {
            Console.WriteLine((i + 1) + " " + result[i]);
        }
    }
}

In Python, we copy the original list into a temporary list for performing swaps. This version retains unaltered access to the initial arrangement of student names.

Complexity

Time Complexity: O(n), traversing the list.
Space Complexity: O(n), for the copied list.

Try this approach in the editor

Approach 3: Default Approach

# Write your MySQL query statement below
SELECT s1.id, COALESCE(s2.student, s1.student) AS student
FROM
    Seat AS s1
    LEFT JOIN Seat AS s2 ON (s1.id + 1) ^ 1 - 1 = s2.id
ORDER BY 1;
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Direct Swap with Traversal

Time Complexity: O(n), where n is the number of students.
Space Complexity: O(1), due to in-place operations.

Approach 2: Use of Temporary Data Structures

Time Complexity: O(n), traversing the list.
Space Complexity: O(n), for the copied list.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
Direct Swap with TraversalO(n)O(1)Best choice when rows are already ordered by seat ID and swaps can be computed directly with conditional logic
Temporary Data StructureO(n)O(n)Useful when implementing the logic in general-purpose languages or when transformations are easier with arrays

Frequently asked questions

Is Exchange Seats easy or hard?

Exchange Seats is generally considered a medium-level database problem. The logic is simple once you recognize the pairwise swapping pattern, but writing a clean SQL query or handling edge cases like the final odd seat requires careful thinking.

Exchange Seats Python/Java solution

In Python or Java, store the seat records in a list and iterate in steps of two. Swap elements at indices i and i+1 while ensuring the loop stops before exceeding the array bounds. The implementation runs in O(n) time and keeps the last element unchanged when the length is odd.

How to solve Exchange Seats in O(n)?

Iterate through the seat records in order and swap adjacent pairs. If a seat ID is odd and another row follows it, exchange it with the next seat. If the ID is even, map it back to the previous seat. A CASE expression or pairwise swap logic completes the operation in a single pass.

What is the best approach for Exchange Seats?

The direct swap with traversal approach is the most efficient. It processes the rows in order and swaps adjacent seat IDs using conditional logic. The algorithm runs in O(n) time with O(1) extra space, making it ideal for both SQL queries and in-memory implementations.

Is Exchange Seats asked at Google/Amazon/Meta?

Exchange Seats represents a common database interview pattern involving row manipulation and conditional logic. Similar seat-swapping or pairwise transformation problems appear in interviews at large tech companies when evaluating SQL reasoning and data transformation skills.

What data structure is used in Exchange Seats?

The problem primarily relies on ordered rows in a database table. In algorithmic implementations, an array or list can store the rows so adjacent elements can be swapped during traversal.

What is the time complexity of Exchange Seats?

The standard solution runs in O(n) time because each seat record is processed once. Only simple comparisons and swaps are performed for each row. Space complexity can be O(1) when swapping logically in a query, or O(n) if a temporary array or table is used.

Comments

Now write it yourselfClose this page and solve Exchange Seats in the editor, without looking.
Practise Exchange Seats