Sponsored
Sponsored
In this approach, you perform a left-to-right scan to compute the distance to the nearest occupied seat on the left and a right-to-left scan to compute the distance to the nearest occupied seat on the right. For each empty seat, the result will be the minimum of these distances. The final solution is the maximum among these minimum distances.
Time Complexity: O(n) where n is the number of seats. We pass over the list twice.
Space Complexity: O(n) due to the use of additional arrays for storing distances.
1function maxDistToClosest(seats) {
2 const n = seats.length;
3 const left = new Array(n).fill(n);
4 const right = new Array(n).fill(n);
5
6 for (let i = 0, last = -1; i < n; i++) {
7 if (seats[i] === 1) last = i;
8 else if (last !== -1) left[i] = i - last;
9 }
10
11 for (let i = n - 1, last = -1; i >= 0; i--) {
12 if (seats[i] === 1) last = i;
13 else if (last !== -1) right[i] = last - i;
14 }
15
16 let maxDist = 0;
17 for (let i = 0; i < n; i++) {
18 if (seats[i] === 0) {
19 const dist = Math.min(left[i], right[i]);
20 maxDist = Math.max(maxDist, dist);
21 }
22 }
23
24 return maxDist;
25}
26
27// Example usage
28console.log(maxDistToClosest([1, 0, 0, 0, 1, 0, 1]));
The JavaScript solution follows the same logic using arrays to track distances from occupied seats. It calculates the maximum possibility for Alex's sitting position by evaluating minimum distances.
This approach involves using a single pass over the seats array while utilizing two pointers. The first pointer stores the last filled seat position, and with each empty seat, the calculation is made based on its distance from the last filled position and the subsequent fill.
Time Complexity: O(n) for a single traversal.
Space Complexity: O(1) since it uses a constant amount of space.
1#include <iostream>
using namespace std;
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
int prev = -1, future = 0, maxDist = 0;
for (int i = 0; i < seats.size(); ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < seats.size() && (seats[future] == 0 || future < i)) {
++future;
}
int leftDist = (prev == -1) ? seats.size() : i - prev;
int rightDist = (future == seats.size()) ? seats.size() : future - i;
int minDist = min(leftDist, rightDist);
maxDist = max(maxDist, minDist);
}
}
return maxDist;
}
};
int main() {
vector<int> seats = {1, 0, 0, 0, 1, 0, 1};
Solution sol;
cout << sol.maxDistToClosest(seats) << endl;
return 0;
}
The C++ solution accomplishes the same task with a minimal, efficient use of variables, aligning one scan of the seat array.