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.
1#include <stdio.h>
2
3int maxDistToClosest(int* seats, int seatsSize) {
4 int left[seatsSize];
5 int right[seatsSize];
6 int maxDist = 0;
7
8 // Left to right pass
9 int lastFilled = -1;
10 for (int i = 0; i < seatsSize; i++) {
11 if (seats[i] == 1) {
12 lastFilled = i;
13 left[i] = 0;
14 } else {
15 left[i] = (lastFilled == -1) ? seatsSize : i - lastFilled;
16 }
17 }
18
19 // Right to left pass
20 lastFilled = -1;
21 for (int i = seatsSize - 1; i >= 0; i--) {
22 if (seats[i] == 1) {
23 lastFilled = i;
24 right[i] = 0;
25 } else {
26 right[i] = (lastFilled == -1) ? seatsSize : lastFilled - i;
27 }
28 }
29
30 // Calculate max of min distances
31 for (int i = 0; i < seatsSize; i++) {
32 if (seats[i] == 0) {
33 int distance = (left[i] < right[i]) ? left[i] : right[i];
34 if (distance > maxDist) maxDist = distance;
35 }
36 }
37
38 return maxDist;
39}
40
41int main() {
42 int seats[] = {1,0,0,0,1,0,1};
43 int size = sizeof(seats) / sizeof(seats[0]);
44 printf("%d\n", maxDistToClosest(seats, size));
45 return 0;
46}
The C solution uses two arrays to keep track of the minimum distances to the nearest person on the left and right. It initializes two separate passes over the seats array: the first pass computes the distance to the last occupied chair on the left, while the second pass computes the distance to the next occupied chair on the right. Finally, it calculates the maximum of the minimum distances for each 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
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.