Maximize Distance to Closest Person
Medium
Topics
nums describes a row of seats, where 1 is occupied and 0 is empty. There is at least one of each.
You want to sit as far as possible from the nearest occupied seat. Return that distance — the largest value of "distance to the closest person" achievable by choosing one empty seat.
Example 1
Input: nums = [1,0,0,0,1,0,1] Output: 2 Explanation: Sitting at index 2 puts you 2 away from the people at 0 and 4. The gap on the right is too small to beat it.
Example 2
Input: nums = [1,0,0,0] Output: 3 Explanation: The last seat has nobody to its right, so only the person at index 0 counts — 3 away.
Example 3
Input: nums = [0,1] Output: 1 Explanation: The only empty seat is next to the only person.
Constraints
- 2 <= nums.length <= 2 * 10^4
- nums[i] is 0 or 1
- At least one seat is occupied and at least one is empty
Editorial — intuition, approach, complexity and pitfalls
Intuition
Only the runs of empty seats matter, and they come in two kinds that score very differently.
A run between two people is best used from its middle, and a run of length g gives a distance of (g + 1) / 2 rounded down — for a gap of 3 that is 2, the middle seat being 2 from each side.
A run at either end of the row has a person on one side only, so the far seat is used and the distance is the whole run length. That is why example 2 answers 3 rather than 2: the same three empty seats are worth more at the edge than they would be in the middle.
The answer is the largest value over all runs, remembering that an edge run is scored by a different formula from an interior one.
Approach
- Find the index of the first and last occupied seat.
- The leading run scores
firstOccupied, and the trailing run scoreslength - 1 - lastOccupied. Either may be zero. - For the interior, measure each gap between consecutive occupied seats and score it as
gap / 2rounded down, wheregapis the index difference. - Return the largest of the three kinds of score.
Walkthrough
nums = [1,0,0,0,1,0,1]
index 0 1 2 3 4 5 6
occupied at 0, 4, 6
leading run : none before index 0 score 0
gap 0 -> 4 : 3 empty seats, best is index 2 score 4/2 = 2
gap 4 -> 6 : 1 empty seat at index 5 score 2/2 = 1
trailing run : none after index 6 score 0
answer 2
---
nums = [1,0,0,0]
occupied at 0 only
leading 0, no interior gap,
trailing run = 3 - 0 = 3 -> answer 3
The same three seats scored 2 as an interior gap above and
3 as a trailing run here, which is the whole point.Complexity
- Time — O(n): one pass to find the occupied seats and one over the gaps between them.
- Space — O(n): the list of occupied indices; tracking only the previous one makes it O(1).
Common Pitfalls
- Scoring an edge run with the interior formula. That is the single most common wrong answer, and it shows up as 2 instead of 3 on example 2.
- Rounding the interior gap up. A gap of 2 index positions holds one empty seat at distance 1, not 2.
- Returning the longest run of empty seats rather than the best distance. A run of 3 in the middle is worth 2.
- Assuming there is at least one person on each side. The constraints only promise one person somewhere.
Full Solution — all languages
class Solution:
def maxDistToClosest(self, nums):
occupied = [i for i, seat in enumerate(nums) if seat == 1]
best = occupied[0]
best = max(best, len(nums) - 1 - occupied[-1])
for a, b in zip(occupied, occupied[1:]):
best = max(best, (b - a) // 2)
return bestimport java.util.*;
class Solution {
public int maxDistToClosest(int[] nums) {
List<Integer> occupied = new ArrayList<>();
for (int i = 0; i < nums.length; i++) if (nums[i] == 1) occupied.add(i);
int best = occupied.get(0);
best = Math.max(best, nums.length - 1 - occupied.get(occupied.size() - 1));
for (int i = 1; i < occupied.size(); i++) {
best = Math.max(best, (occupied.get(i) - occupied.get(i - 1)) / 2);
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int maxDistToClosest(vector<int>& nums) {
vector<int> occupied;
for (size_t i = 0; i < nums.size(); i++) if (nums[i] == 1) occupied.push_back((int)i);
int best = occupied[0];
best = max(best, (int)nums.size() - 1 - occupied.back());
for (size_t i = 1; i < occupied.size(); i++) {
best = max(best, (occupied[i] - occupied[i - 1]) / 2);
}
return best;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var maxDistToClosest = function(nums) {
const occupied = [];
for (let i = 0; i < nums.length; i++) if (nums[i] === 1) occupied.push(i);
let best = occupied[0];
best = Math.max(best, nums.length - 1 - occupied[occupied.length - 1]);
for (let i = 1; i < occupied.length; i++) {
best = Math.max(best, Math.floor((occupied[i] - occupied[i - 1]) / 2));
}
return best;
};