Middle
Explain the technique for solving the problem of maximum distance to the nearest occupied seat.
sobes.tech AI
Answer from AI
The problem of finding the maximum distance to the nearest occupied seat is often formulated as follows: there is a row of seats (for example, benches or chairs), some of which are occupied (marked as 1), and the rest are free (0). The task is to find a free seat that is maximally distant from the nearest occupied one.
Solution technique:
- Iterate through the array and for each free seat, calculate the distance to the nearest occupied seat.
- It is convenient to use two passes for this:
- From left to right: record the distance to the nearest occupied seat on the left for each seat.
- From right to left: do the same for the right side.
- For each free seat, take the minimum of the two distances — this is the distance to the nearest occupied seat.
- Find the maximum among these minimum distances.
Example in Go:
func maxDistToClosest(seats []int) int {
n := len(seats)
leftDist := make([]int, n)
rightDist := make([]int, n)
// Initialization
for i := 0; i < n; i++ {
leftDist[i] = n
rightDist[i] = n
}
// From left to right
for i := 0; i < n; i++ {
if seats[i] == 1 {
leftDist[i] = 0
} else if i > 0 {
leftDist[i] = leftDist[i-1] + 1
}
}
// From right to left
for i := n - 1; i >= 0; i-- {
if seats[i] == 1 {
rightDist[i] = 0
} else if i < n-1 {
rightDist[i] = rightDist[i+1] + 1
}
}
maxDist := 0
for i := 0; i < n; i++ {
if seats[i] == 0 {
dist := leftDist[i]
if rightDist[i] < dist {
dist = rightDist[i]
}
if dist > maxDist {
maxDist = dist
}
}
}
return maxDist
}
This approach is efficient and works in O(n) time.