1156. Arithmetic Range Adds

Medium3.5 points estimatedPrefix SumArraySimulation

A conveyor has n bins, numbered from 0 and all empty. Each request [l, r] in ramps pours grains in a staircase: bin l gets 1 grain, bin l + 1 gets 2 grains, and so on, up to bin r, which gets r - l + 1 grains. If l > r, swap the two ends first. The grains of different requests accumulate in the same bins.

Return an array of length n with the grain count of every bin after all requests, as 64-bit integers. Constraints: 1 <= n <= 2*10^5, 1 <= ramps.length <= 10^5, 0 <= l, r < n, and every final value is at most 2*10^10. Aim for O(n + ramps.length) time and O(n) space.

Example 1

Input:
n = 5, ramps = [[1,3]]
Output:
[0,1,2,3,0]
Explanation:

One ramp over bins 1 to 3 adds 1, 2, 3, so the bins end as [0, 1, 2, 3, 0].

Example 2

Input:
n = 4, ramps = [[0,3],[2,1]]
Output:
[1,3,5,4]
Explanation:

The first ramp gives [1, 2, 3, 4]; the second has its ends swapped to [1, 2] and adds 1 and 2 to bins 1 and 2, giving [1, 3, 5, 4].

Example 3

Input:
n = 1, ramps = [[0,0]]
Output:
[1]
Explanation:

A ramp over a single bin adds 1 grain.

Constraints

1 ≤ n ≤ 2*105
1 ≤ ramps.length ≤ 105
0 ≤ l, r < n
every final value ≤ 2*1010

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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n + q)
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…