Maximize Distance to Closest Person - Problem
Cinema Seating Problem: You're entering a movie theater represented by an array seats, where seats[i] = 1 means someone is already sitting in seat i, and seats[i] = 0 means the seat is empty.

Your goal is to find the optimal seat that maximizes your distance from the nearest occupied seat. Think of it as finding the most "private" spot in the theater!

Example: In seats [1,0,0,0,1,0,1], you'd want to sit at index 2 because it's distance 2 from the nearest person (at indices 0 and 4).

Return: The maximum possible distance to the closest person.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1,0,0,0,1,0,1]
โ€บ Output: 2
๐Ÿ’ก Note: Sitting at index 2 gives distance 2 to nearest people at indices 0 and 4. This is the maximum possible distance.
example_2.py โ€” Edge Seat
$ Input: [1,0,0,0]
โ€บ Output: 3
๐Ÿ’ก Note: Sitting at the rightmost seat (index 3) gives distance 3 from the person at index 0. Edge seats can provide maximum distance.
example_3.py โ€” Multiple Options
$ Input: [0,1,0,0,0,1,0]
โ€บ Output: 2
๐Ÿ’ก Note: The optimal seats are at indices 3 or 4, both giving distance 2 to the nearest occupied seats.

Constraints

  • 2 โ‰ค seats.length โ‰ค 2 ร— 104
  • seats[i] is either 0 or 1
  • At least one seat is empty (seats[i] = 0)
  • At least one seat is occupied (seats[i] = 1)

Visualization

Tap to expand
๐Ÿ‘ค๐Ÿ’บ๐Ÿ’บ๐ŸŽฏ๐Ÿ’บ๐Ÿ‘ค๐Ÿ’บDistance: 3Distance: 2Optimal Choice: Min distance = 2๐ŸŽฌ Movie Theater Layout
Understanding the Visualization
1
Scan Theater Layout
Identify all occupied (1) and empty (0) seats in the row
2
Calculate Left Distances
For each seat, find distance to nearest person on the left
3
Calculate Right Distances
For each seat, find distance to nearest person on the right
4
Find Optimal Seat
Choose the empty seat with maximum distance to closest person
Key Takeaway
๐ŸŽฏ Key Insight: The optimal seat maximizes the distance to the nearest person, which occurs either at the ends of the row or in the center of the largest gap between occupied seats.
Asked in
Google 28 Amazon 22 Meta 15 Apple 12
78.3K Views
Medium Frequency
~15 min Avg. Time
1.9K 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