(126). 32.5. HASHING‐NUMBER OF SUBARRAYS WITH SUM ZERO - anishsingh90/Data_Structure_And_Algorithm_In_Cpp_github.io GitHub Wiki

#include #include #include using namespace std;

int main() { int n; cout << "Enter the size of array: "; cin >> n;

vector<int> a(n);
for (int i = 0; i < n; i++) {
    cin >> a[i];
}

map<int, int> cnt;
int prefSum = 0;
long long ans = 0; // Initialize ans as long long

for (int i = 0; i < n; i++) {
    prefSum += a[i];
    cnt[prefSum]++;
}

map<int, int>::iterator it;

for (it = cnt.begin(); it != cnt.end(); it++) {
    int c = it->second; // Use it->second instead of it->ss

    ans += (static_cast<long long>(c) * (c - 1)) / 2; // Cast c to long long

    if (it->first == 0) {
        ans += it->second;
    }
}

cout <<"Number of subarray which sum is zero: "<< ans << endl;

return 0;

}

/* OUTPUT: Enter the size of array: 4 1 -1 1 -1 Number of subarray which sum is zero: 4 */

⚠️ **GitHub.com Fallback** ⚠️