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 Person INPUT seats = [1,0,0,0,1,0,1] 1 0 0 0 1 0 1 0 1 2 3 4 5 6 = Person sitting = Empty seat Gaps to analyze: Left edge, Middle, Right edge seats = [1,0,0,0,1,0,1] ALGORITHM STEPS 1 Find all gaps Identify consecutive 0s 2 Gap 1: Left edge Index 0 has person: dist=0 3 Gap 2: Middle [1-3] 3 empty seats, dist = 3/2 = 2 1 0 0 0 1 Best: idx 2 4 Gap 3: [5] and right 1 empty seat, dist = 1 Distance Formula: Middle gap: (gap_size+1)/2 Edge gap: gap_size max(0, 2, 1) = 2 FINAL RESULT Alex sits at index 2 1 0 Alex 0 1 0 1 dist = 2 dist = 2 OUTPUT 2 Verification: Closest person to Alex is 2 seats away OK - Maximum achieved! Key Insight: For gaps between two people, the best seat is in the middle (distance = gap_size/2). For edge gaps (start or end), Alex can sit at the edge (distance = gap_size). Track three cases: left edge gap, middle gaps, and right edge gap. Return the maximum distance found. TutorialsPoint - Maximize Distance to Closest Person | Gap Analysis Approach
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