#849
Maximize Distance to Closest Person
MediumArrayArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the observation that the maximum distance can be found by considering the edges of the occupied seats and the gaps between them. We can calculate the maximum distance directly without nested loops.
⚙️
Algorithm
4 steps- 1Step 1: Initialize variables for the maximum distance and the previous occupied seat index.
- 2Step 2: Traverse the seats array to find the first occupied seat and handle leading zeros.
- 3Step 3: For each subsequent occupied seat, calculate the distance to the previous occupied seat and update the maximum distance accordingly.
- 4Step 4: Handle trailing zeros after the last occupied seat.
solution.py12 lines
1def maxDistToClosest(seats):
2 max_distance = 0
3 prev = -1
4 for i in range(len(seats)):
5 if seats[i] == 1:
6 if prev == -1:
7 max_distance = i # Leading zeros
8 else:
9 max_distance = max(max_distance, (i - prev) // 2)
10 prev = i
11 max_distance = max(max_distance, len(seats) - 1 - prev) # Trailing zeros
12 return max_distanceℹ
Complexity note: This complexity is linear because we only make a single pass through the array, checking each seat once.
- 1The distance to the closest person can be maximized by considering both leading and trailing empty seats.
- 2The optimal solution reduces unnecessary calculations by leveraging the positions of occupied seats.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.