Problem · Array
Count Zero-Sum Fragments
Learn this problemProblem statement
Write a function solution that, given an array A consisting of N integers, returns the number of fragments of A whose sum equals 0 (that is, pairs (P, Q) such that P <= Q and the sum A[P] + A[P+1] + ... + A[Q] is 0). The function should return -1 if this number exceeds 1,000,000,000.
The source also states: given A = [0, 0, ..., 0] of length 100,000, the function should return -1.
Function
solution(A: int[]) → intExamples
Example 1
A = [2, -2, 3, 0, 4, -7]return = 4
The zero-sum fragments shown in the source picture are:
[2, -2][0][3, 0, 4, -7][2, -2, 3, 0, 4, -7]
Constraints
Write an efficient algorithm for the following assumptions:
Nis an integer within the range[1..100,000].- Each element of array
Ais an integer within the range[-10,000..10,000].