1271. Dual Tally Stretches

Two teams play a series of rounds. In round i the first team scores a[i] points and the second team scores b[i] points; scores may be negative because of penalties. A commentator looks at stretches of consecutive rounds that cover at least minLen rounds and asks whether the two teams earned exactly the same total points over the stretch.

Return how many such stretches exist, as a long. Stretches with different start or end rounds are different. Both arrays have the same length. Build prefix totals of a[i] - b[i]; two prefix positions that are at least minLen apart and hold equal totals form a stretch, so only add a prefix to your hash map once it is far enough behind the current position.

The intended solution runs in O(n) time and O(n) space.

Example 1

Input:
a = [3,-2,5,4,1,0], b = [1,0,7,2,3,0], minLen = 2
Output:
5
Explanation:

Stretches of at least 2 rounds with equal totals are rounds 0..1, 0..3, 2..3, 3..4 and 3..5, so the answer is 5.

Example 2

Input:
a = [12,-4,9,-4,6], b = [5,-3,-1,12,3], minLen = 1
Output:
1
Explanation:

Only rounds 0..3 give equal totals: the first team gets 12-4+9-4 = 13 and the second gets 5-3-1+12 = 13, so the answer is 1.

Example 3

Input:
a = [-6,2,9,-11,7,4], b = [2,-3,-2,5,-1,8], minLen = 3
Output:
2
Explanation:

With stretches of at least 3 rounds, rounds 0..4 and 1..3 are the only ones with equal totals, so the answer is 2.

Constraints

1 ≤ a.length == b.length ≤ 2 * 105

-104 ≤ a[i], b[i] ≤ 104

1 ≤ minLen ≤ a.length

The answer needs a 64-bit integer.

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