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.
1from typing import List
2
3class Solution:
4 def maxDistToClosest(self, seats: List[int]) -> int:
5 n = len(seats)
6 left = [n] * n
7 right = [n] * n
8
9 for i in range(n):
10 if seats[i] == 1:
11 left[i] = 0
12 elif i > 0:
13 left[i] = left[i-1] + 1
14
15 for i in range(n-1, -1, -1):
16 if seats[i] == 1:
17 right[i] = 0
18 elif i < n - 1:
19 right[i] = right[i+1] + 1
20
21 return max(min(left[i], right[i]) for i in range(n) if seats[i] == 0)
22
23# Example usage
24sol = Solution()
25seats = [1, 0, 0, 0, 1, 0, 1]
26print(sol.maxDistToClosest(seats))
The Python solution takes a slightly different approach to handling the calculations within the same loop for each direction and uses list comprehensions to calculate the maximum of the minimal 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
public class Solution {
public int MaxDistToClosest(int[] seats) {
int prev = -1, future = 0, maxDist = 0;
for (int i = 0; i < seats.Length; ++i) {
if (seats[i] == 1) {
prev = i;
} else {
while (future < seats.Length && (seats[future] == 0 || future < i)) {
future++;
}
int leftDist = (prev == -1) ? seats.Length : i - prev;
int rightDist = (future == seats.Length) ? seats.Length : future - i;
int minDist = Math.Min(leftDist, rightDist);
maxDist = Math.Max(maxDist, minDist);
}
}
return maxDist;
}
public static void Main(string[] args) {
int[] seats = { 1, 0, 0, 0, 1, 0, 1 };
Solution sol = new Solution();
Console.WriteLine(sol.MaxDistToClosest(seats));
}
}
The C# solution mirrors these techniques within the language's syntax, generally computing distances within a single linear pass.