You are given an array representing a row of seats where seats[i] = 1
represents a person sitting in the i-th
seat, and seats[i] = 0
represents that the i-th
seat is empty (0-indexed).
There is at least one empty seat, and at least one person sitting.
Alex wants to sit in the seat such that the distance to the closest person is maximized. Return that maximum distance to the closest person.
seats = [1,0,0,0,1,0,1]
2
seats = [1,0,0,0]
3
seats = [0,1]
1
1
and at least one 0
?
To solve the problem, we need to consider three main cases:
We can use a linear scan to determine these values. During the scan:
The main steps:
def maxDistToClosest(seats):
n = len(seats)
last_person = -1
max_dist = 0
for i in range(n):
if seats[i] == 1:
if last_person == -1:
max_dist = i
else:
max_dist = max(max_dist, (i - last_person) // 2)
last_person = i
max_dist = max(max_dist, n - last_person - 1)
return max_dist
The code runs in O(n) time complexity as we are iterating through the list once to determine the distance. This ensures it’s efficient even for large inputs. The space complexity is O(1) because we are using a constant amount of extra space regardless of input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?