
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.
Solve with full IDE support and test cases
This Java solution is similar in nature, using two arrays to calculate distances from left and right before determining the maximum distance for Alex's optimal seat.
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 <stdio.h>
2
3int maxDistToClosest(int* seats, int seatsSize) {
4 int prev = -1;
5 int future = 0;
6 int maxDist = 0;
7
8 for (int i = 0; i < seatsSize; ++i) {
9 if (seats[i] == 1) {
10 prev = i;
11 } else {
12 while (future < seatsSize && seats[future] == 0 || future < i) {
13 future++;
14 }
15 int leftDist = (prev == -1) ? seatsSize : i - prev;
16 int rightDist = (future == seatsSize) ? seatsSize : future - i;
17 int minDist = (leftDist < rightDist) ? leftDist : rightDist;
18 if (minDist > maxDist) maxDist = minDist;
19 }
20 }
21
22 return maxDist;
23}
24
25int main() {
26 int seats[] = {1,0,0,0,1,0,1};
27 int size = sizeof(seats) / sizeof(seats[0]);
28 printf("%d\n", maxDistToClosest(seats, size));
29 return 0;
30}In this C solution, a single pass evaluates each seat while dynamically adjusting two pointers (prev for the last occupied position and future for the next occupied position) to compute potential seat distances.