Problem 849

Abstract / Summary

Find the maximum distance to the closest person when placing someone in a row of seats.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
20 lines | 601 bytes | submitted October 9, 2023 | GitHub   5% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 50% (500k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.33 | σ = 1.31

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
33 links | 20 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

3 easy 7 medium 1 hard
12 solutions   October 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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