1407. Final Paint Visibility

A mural is painted along a number line with strokes applied in index order. Stroke i covers the half-open range [starts[i], starts[i] + lengths[i]) and is painted on top of everything painted before it. After all strokes are done, return an array where entry i is the total length of stroke i that is still visible, as longs.

Process the strokes in reverse and let each one claim only the stretches nobody later has claimed. Keeping the unpainted gaps in an ordered set, or a union-find that jumps to the next unpainted segment over compressed coordinates, means every stretch is claimed once. The result has the same length as the input arrays. The intended solution runs in O(n log n) time and O(n) space.

Example 1

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

Stroke 0 shows only its first cell, stroke 1 shows cells 3 to 5, and stroke 2 covers cells 1 and 2 on top.

Example 2

Input:
starts = [5], lengths = [7]
Output:
[7]
Explanation:

A single stroke is fully visible.

Example 3

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

The second stroke covers the whole range of the first, so the first has nothing visible.

Constraints

1 ≤ n ≤ 105, starts.length == lengths.length

0 ≤ starts[i] ≤ 109

1 ≤ 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 7,200 msC++ 1,800 msJava 3,600 msJavaScript 3,600 msTypeScript 3,600 ms

Expected complexity

Time
O(n log 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…