Similar Problems
Similar Problems not available
Exchange Seats - Leetcode Solution
LeetCode: Exchange Seats Leetcode Solution
Difficulty: Medium
Topics: database
The Exchange Seats problem on leetcode requires swapping the seats of n students in a classroom. The positions are represented as a 0-indexed integer array seats, where seats[i] is the position of the ith seat. Each student has a seat number between 0 and n-1 inclusive. Swaps can be performed only on adjacent seats.
The solution to this problem involves iterating through the array and swapping adjacent seats if they are unoccupied. If both are occupied, then there is no need to swap.
To swap seats, we simply interchange the values of the two indices.
The implementation for this solution is straightforward :
class Solution {
public int[] seatsExchange(int[] seats) {
int n = seats.length;
for (int i = 0; i < n - 1; i++) {
if (seats[i] == 0 && seats[i + 1] == 1) {
int temp = seats[i];
seats[i] = seats[i + 1];
seats[i + 1] = temp;
}
}
return seats;
}
}
To optimize the solution, we can also reduce the number of iterations by considering only even or odd indices in each iteration.
class Solution {
public int[] seatsExchange(int[] seats) {
int n = seats.length;
for (int i = 0; i < n - 1; i += 2) {
if (seats[i] == 0 && seats[i + 1] == 1) {
int temp = seats[i];
seats[i] = seats[i + 1];
seats[i + 1] = temp;
}
}
for (int i = 1; i < n - 1; i += 2) {
if (seats[i] == 0 && seats[i + 1] == 1) {
int temp = seats[i];
seats[i] = seats[i + 1];
seats[i + 1] = temp;
}
}
return seats;
}
}
This implementation reduces the number of iterations by half and hence improves the time complexity of the algorithm.
The time complexity of the first implementation is O(n) and that of the second implementation is O(n/2).
The space complexity of both implementations is O(1).
Exchange Seats Solution Code
1