1488. Spaced Picks From Ranges

Medium3.5 points estimatedBinary SearchGreedySorting

A festival planner has n stalls to place along a street. Stall i may be set up at any whole-number position from starts[i] to starts[i] + d, both ends included, and every stall has the same flexibility d. Two stalls may share a position, but the planner wants the visitors to be spread out: the smallest distance between any two chosen positions should be as large as possible.

Given the array starts and the integer d, choose one position per stall and return the largest possible value of the minimum absolute difference between any two chosen positions. The answer for a single choice is the smallest gap, and you want the best such value over all choices, so no tie-break is needed. Aim for O(n log n + n log M) time, where M is the largest possible gap, and O(n) extra space.

Example 1

Input:
starts = [1,5,9], d = 2
Output:
5
Explanation:

Choose 1, 6 and 11; the closest pair is 5 apart, and no choice does better.

Example 2

Input:
starts = [4,4,4], d = 3
Output:
1
Explanation:

All ranges are [4,7]; picks 4, 5 and 7 keep every pair at least 1 apart, but 2 is impossible.

Example 3

Input:
starts = [10,0], d = 0
Output:
10
Explanation:

With d = 0 the positions are fixed at 0 and 10, so the gap is 10.

Constraints

2 ≤ n ≤ 105

0 ≤ starts[i] ≤ 5*108

0 ≤ d ≤ 5*108

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n log n + n log M)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…