Count Subarrays with Equal Prefix SumsMedium

Count Subarrays with Equal Prefix Sums

MediumPractice library · +20 XPprefix sumshash mapcounting

Given an array of N integers, find the number of pairs of indices (i, j) such that 0 <= i < j < N and the prefix sum up to index i-1 is equal to the prefix sum up to index j-1. The prefix sum up to index k is defined as the sum of elements from index 0 to k (inclusive). The prefix sum up to index -1 (before the first element) is considered to be 0.

Input

The first line contains a single integer N, the size of the array. The second line contains N space-separated integers, representing the elements of the array.

Output

A single integer representing the total count of pairs (i, j) satisfying the condition.

Constraints

1 <= N <= 200000. The array elements are integers between -10^9 and 10^9.

Time limit 2 s (native code; slower languages get more)Memory 256 MB13 hidden tests

Example 1

Input
5
1 2 -1 -2 3
Output
2

Prefix sums (including initial 0): [0, 1, 3, 2, 0, 3]. Pairs with equal sums: (0, 3) for value 0, (1, 4) for value 3. Count = 2.

Example 2

Input
3
0 0 0
Output
6

Prefix sums: [0, 0, 0, 0]. Pairs: (0,1), (0,2), (0,3), (1,2), (1,3), (2,3). Count = 6.

Hints