Python 0849.py
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
space = [ 0 ]
for s in seats:
if s == 0:
space[-1] += 1
else:
if space[-1] > 0:
space.append(0)
# space[i] must be > 0
if space[0] == 0:
space.pop(0)
if space[-1] == 0:
space.pop(-1)
middle = (max(space) + 1) // 2
left = space[ 0] if seats[ 0] == 0 else 0
right = space[-1] if seats[-1] == 0 else 0
return max(left, middle, right)
Difficulty
and has an acceptance rate of about 50% (500k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the maximum distance a new person can sit from the closest occupied seat in a linear row of seats. It does this by first collapsing the input into a compact representation of consecutive empty seats, then extracting the longest possible distance from three distinct scenarios: an empty stretch at the left end, an empty stretch at the right end, and an empty stretch surrounded by occupied seats. The final answer is the greatest of these three values.
Step 1: Collapse consecutive empty seats
The algorithm iterates through the seats list once, maintaining a list called space. The first element of space is initialized to zero, representing a potential leading gap. For each seat, if the seat is empty (0), the current gap length (space[-1]) is incremented. When an occupied seat (1) is encountered, the code checks whether the current gap length is non-zero; if it is, a new gap entry is started by appending a zero to space. This yields a sequence where each positive entry corresponds to a block of empty seats, and zero entries mark the boundaries between gaps.
space = [0]
for s in seats:
if s == 0:
space[-1] += 1
else:
if space[-1] > 0:
space.append(0)
Step 2: Trim non-existent edge gaps
After the first pass, the space list may contain leading or trailing zeros that do not correspond to actual empty stretches (for example, when the row starts or ends with an occupied seat). The code removes these sentinel zeros by checking the first and last elements and popping them when they are zero. This ensures that every remaining entry in space represents a genuine block of empty seats.
if space[0] == 0:
space.pop(0)
if space[-1] == 0:
space.pop(-1)
Step 3: Compute candidate distances
Three candidate distances are derived:
- Middle gaps - For a block of empty seats surrounded by occupied seats, the optimal position is at the midpoint. The distance is calculated as
(max(space) + 1) // 2, which effectively rounds up the half-length of the longest middle gap. - Left edge - If the first seat is empty, the entire first block of zeros can be used, and the distance equals the length of that block (
space[0]). Otherwise the left candidate is zero. - Right edge - Analogously, if the last seat is empty, the distance equals the length of the final block (
space[-1]); otherwise it is zero.
middle = (max(space) + 1) // 2
left = space[0] if seats[0] == 0 else 0
right = space[-1] if seats[-1] == 0 else 0
Step 4: Return the maximum distance
The final result is the greatest among the three candidates, representing the best possible placement for the new person.
return max(left, middle, right)
Edge Cases Handled
The algorithm gracefully deals with rows that begin or end with empty seats. By trimming leading and trailing zeros from space, it distinguishes between genuine edge gaps and internal gaps. When the row starts with an empty seat, left captures the full length of the leading block; similarly, right captures the trailing block when the row ends with empties. If the row contains no leading or trailing empties, both left and right evaluate to zero, leaving the middle calculation as the sole contributor.
Another subtle edge case is a single long block of empties surrounded by occupied seats. The max(space) call correctly identifies this block, and the integer division formula (max(space) + 1) // 2 yields the correct rounded-up half distance, ensuring the new person sits as far as possible from both neighbors.
Performance Optimizations
The solution achieves its goal with a single linear traversal of the input list, building the space structure on the fly. This eliminates the need for auxiliary passes to locate occupied seats or to compute distances for each empty seat individually. By storing only the lengths of empty stretches, the algorithm reduces memory usage to a size proportional to the number of gaps rather than the total number of seats.
The use of integer arithmetic for the middle distance ((max(space) + 1) // 2) avoids floating-point operations and additional rounding logic, delivering a fast, deterministic calculation. The final max call operates on just three scalar values, keeping the concluding step trivial in terms of computational effort.
ELI5 - Simplified Explanation
Imagine a long row of chairs in a movie theater where some are taken by people and some are empty. The goal is to pick an empty seat that stays as far away from everyone else as possible.
The code starts by looking at the whole row and counting how many empty chairs are in each empty group. It ignores the chairs where people are already sitting.
Next, the code checks the very beginning and the very end of the row. If there are empty chairs at the start or the very end, those act like special spots because nobody is sitting on one side of them.
Then, the code makes a few comparisons. It looks at the group of empty chairs in the middle of two people and calculates the biggest gap it can find by splitting that space in half. It also looks at the empty space at the very start and the very end of the row. Finally, it picks the largest number out of all those options to find the best place to sit while staying as far from other people as possible.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | BigEggStudy | C# | |||||||
| black-shadows | C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| BigEggStudy | C# | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| haoel | Python | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| YuriSpiridonov | Python | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 855: Exam Room
- problem 2365: Task Scheduler II
Solved On The Same Day
- problem 812: Largest Triangle Area
- problem 824: Goat Latin
- problem 844: Backspace String Compare
- problem 791: Custom Sort String
- problem 794: Valid Tic-Tac-Toe State
- problem 807: Max Increase to Keep City Skyline
- problem 813: Largest Sum of Averages
- problem 814: Binary Tree Pruning
- problem 825: Friends Of Appropriate Ages
- problem 848: Shifting Letters
- problem 815: Bus Routes
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality