You are given an array representing a row of seats in a theater, where 1 represents an occupied seat and 0 represents an empty seat. You want to sit in an empty seat such that your distance to the closest person already sitting there is maximized. You must return that maximum distance.
This is a classic linear array traversal problem. Interviewers use it to see if a candidate can handle three distinct edge cases elegantly: sitting at the far left edge, sitting at the far right edge, and sitting somewhere in the middle between two people. It tests your ability to write clean, localized sliding window logic without complicated math.
This problem relies on a Two Pointers (Sliding Window) or Gap Counting pattern.
You iterate through the array to find the gaps of 0s between 1s.
1), the maximum distance is exactly the size of the gap.1 to the end of the array), the maximum distance is also exactly the size of the gap.1s in the middle, the optimal seat is in the exact center of the gap. The distance to the closest person is gap_length / 2 (or more specifically, (right_index - left_index) / 2).
You return the maximum of these three scenarios.Seats: [1, 0, 0, 0, 1, 0, 1]
1 is at index 0. No left gap.1 is at index 4. The gap of zeroes is [1, 2, 3]. Length is 4 - 0 = 4. Middle distance = 4 / 2 = 2. (If we sit at index 2, distance to 0 is 2, distance to 4 is 2).1 is at index 6. Gap of zeroes is [5]. Middle distance = (6 - 4) / 2 = 1.Let's look at [0, 0, 1, 0].
The most common mistake is applying the gap / 2 logic to the beginning and end of the array. If you have [0, 0, 0, 1], and you sit at index 0, your distance is 3! If you apply the middle formula, you might divide it by 2 and return 1, which is entirely wrong. You must explicitly track the first 1 and last 1 to handle the boundaries.
For the Maximize Distance to Closest Person coding problem, the cleanest way to write the code is to maintain a prev variable tracking the index of the last seen 1 (initialized to -1). When iterating, if you see a 1, handle the left edge case if prev == -1, and the middle case if prev != -1. After the loop, handle the right edge case using n - 1 - prev. This structure guarantees no edge case is forgotten.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximum Value of an Ordered Triplet II | Medium | Solve | |
| Number of Adjacent Elements With the Same Color | Medium | Solve | |
| Insert Interval | Medium | Solve | |
| All Divisions With the Highest Score of a Binary Array | Medium | Solve | |
| Remove Interval | Medium | Solve |