1720. Domino Chain Reach

Dominoes stand in a row along a line. Domino i is placed at position p[i] = gaps[0] + gaps[1] + ... + gaps[i], so positions strictly increase, and it has height heights[i]. If domino i is pushed to the right it knocks over every domino whose position lies in the range from p[i] + 1 to p[i] + heights[i] - 1, and each of those falls to the right in the same way, possibly toppling more. For every index i, return how many dominoes fall (domino i itself included) when only domino i is pushed. There are 1 to 100000 dominoes, gaps are 1 to 10^4 and heights 1 to 10^9, so use 64-bit arithmetic for reaches. Aim for O(n) time and O(n) space by sweeping right to left with a stack of merged chain blocks.

Example 1

Input:
gaps = [1,1,1], heights = [2,1,1]
Output:
[2,1,1]
Explanation:

Positions are 1, 2, 3; domino 0 reaches position 2 and topples domino 1, which only has height 1, so the counts are [2, 1, 1].

Example 2

Input:
gaps = [1,2,1,3], heights = [3,2,4,1]
Output:
[4,3,2,1]
Explanation:

Positions are 1, 3, 4, 7; domino 0 topples 1, which topples 2, which reaches position 7 and topples 3, so the counts are [4, 3, 2, 1].

Example 3

Input:
gaps = [5], heights = [1000000000]
Output:
[1]
Explanation:

A single domino only topples itself.

Constraints

1 ≤ n ≤ 105

1 ≤ gaps[i] ≤ 104

1 ≤ heights[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…