Maximize Distance to Closest Person - Problem

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 between him and the closest person to him is maximized. Return that maximum distance to the closest person.

Input & Output

Example 1 — Basic Gap
$ Input: seats = [1,0,0,0,1,0,1]
Output: 2
💡 Note: The largest gap is between positions 0 and 4. Sitting at position 2 gives distance 2 to the closest person.
Example 2 — End Position
$ Input: seats = [1,0,0,0]
Output: 3
💡 Note: Sitting at the rightmost position (index 3) gives distance 3 to the person at index 0.
Example 3 — Multiple Gaps
$ Input: seats = [0,1,0,0,0,1,0]
Output: 2
💡 Note: The gap between positions 1 and 5 has length 3, so sitting in the middle gives distance 2.

Constraints

  • 2 ≤ seats.length ≤ 2 × 104
  • seats[i] is 0 or 1
  • At least one seat is empty
  • At least one seat is occupied

Visualization

Tap to expand
Maximize Distance to Closest PersonInput: [1,0,0,0,1,0,1]1000101↓ Find best empty seat position ↓A22Output: 2 (maximum distance)
Understanding the Visualization
1
Input
Array of seats with 1=occupied, 0=empty
2
Process
Find position that maximizes distance to closest person
3
Output
Return the maximum possible distance
Key Takeaway
🎯 Key Insight: The optimal seat is either at the ends or in the middle of the largest gap between people
Asked in
Google 25 Amazon 20 Facebook 15
32.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen