1375. Almost Common Moment

Medium3.5 points estimatedIntervalsPrefix SumArray

A study group has n members, and member i is free during the closed segment from starts[i] to starts[i] + lengths[i]. The organizer will drop exactly one member and then look for time when all the remaining n - 1 members are free together.

Return the largest possible length of that common time over every choice of the dropped member. The common time of a group is max(0, minEnd - maxStart), where minEnd is the smallest end and maxStart the largest start among the group. Return it as a 64-bit integer; the answer is 0 when no choice leaves any shared time.

Build prefix and suffix arrays of the running maximum start and minimum end so each removal is answered in O(1). Target O(n) time and O(n) space.

Example 1

Input:
starts = [0,4,10], lengths = [5,5,2]
Output:
1
Explanation:

Segments are [0,5], [4,9], [10,12]; dropping the third leaves a common stretch [4,5] of length 1, which is the best.

Example 2

Input:
starts = [0,0], lengths = [7,3]
Output:
7
Explanation:

Dropping either member leaves one segment, so the answer is the longer one, 7.

Example 3

Input:
starts = [1,2,3], lengths = [0,0,0]
Output:
0
Explanation:

All segments are single points at different places, so no choice shares any time and the answer is 0.

Constraints

  • 2 ≤ n ≤ 105, where n is the length of starts
  • starts.length == lengths.length
  • 0 ≤ starts[i], lengths[i] ≤ 109

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)
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…