1382. Coverage Histogram

Medium3.5 points estimatedLine SweepPrefix SumSortingCounting

A fibre network has n cable segments laid along a number line. Segment i occupies every integer position from starts[i] to starts[i] + lengths[i], both ends included, so it covers lengths[i] + 1 integer positions. Arrays starts and lengths both have length n.

Return an array hist of length n where hist[c - 1] is the number of integer positions that are covered by exactly c segments, for every c from 1 to n. Positions covered by no segment are not counted anywhere. The counts can exceed 32 bits, so return them as 64-bit integers.

Turn every segment into a +1 event at its start and a -1 event at start + length + 1, sort the events, and credit each stretch between consecutive event positions to the current coverage. The intended solution runs in O(n log n) time with O(n) space.

Example 1

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

Segment 0 covers 0..3, segment 1 covers 2..5 and segment 2 covers only 10; positions 0,1,4,5 and 10 have one cover (5 in total) and positions 2,3 have two.

Example 2

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

A single segment of length 0 covers only position 7, so hist[0] = 1.

Example 3

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

All three segments cover 1..3, so exactly 3 positions are covered three times.

Constraints

1 ≤ n ≤ 105

starts.length == lengths.length == n

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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 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…