Maximize Distance to Closest Person

You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith 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.

30:00

Maximize Distance to Closest Person
medium
Free written solution
Topics
Companies

You are given an array representing a row of seats where seats[i] = 1 represents a person sitting in the ith seat, and seats[i] = 0 represents that the ith 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.

Example 1:
Input: {"seats":[1,0,0,0,1,0,1]}
Output: 2
Constraints:
  • 2≤seats.length≤2×1042 \leq \text{seats.length} \leq 2 \times 10^4

  • seats[i]\text{seats}[i] is 0 or 1.

  • At least one seat is empty.

  • At least one seat is occupied.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"seats":[1,0,0,0,1,0,1]}

No person seen yet, so prev = -1. Every run of empty seats is a gap; Alex sits in the spot of a gap that is farthest from both ends.

row of seats: blue = person, orange band = gap being measured, pink A = where Alex would sit

0

1

2

3

4

5

6

last person (prev)

-1

best distance

0

Variables
VariableValue
i-
prev-1
best0
DepthFunction Call
Stack empty
0/12