jayati

Zero Sum Subarrays

Sep 17th, 2023
783
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial function template for C++
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function template for C++
  10.  
  11. class Solution{
  12. public:
  13.     //Function to count subarrays with sum equal to 0.
  14.     long long int findSubarray(vector<long long int> &arr, int n ) {
  15.         //code here
  16.         unordered_map<long long int,long long int> m;
  17.         int sum=0;
  18.         int ans=0;
  19.         m[0]=1;
  20.         for(int i=0;i<n;i++)
  21.         {
  22.             sum+=arr[i];
  23.            
  24.             if(m.find(sum)!=m.end())
  25.             {
  26.                 ans+=m[sum];
  27.             }
  28.            
  29.            
  30.            
  31.             m[sum]++;
  32.            
  33.            
  34.         }
  35.         return ans;
  36.     }
  37. };
  38.  
  39. //{ Driver Code Starts.
  40. int main()
  41.  {
  42.     int t;
  43.     cin>>t;
  44.     while(t--)
  45.     {
  46.         int n;
  47.         cin>>n; //input size of array
  48.        
  49.         vector<long long int> arr(n,0);
  50.        
  51.         for(int i=0;i<n;i++)
  52.             cin>>arr[i]; //input array elements
  53.         Solution ob;
  54.         cout << ob.findSubarray(arr,n) << "\n";
  55.     }
  56.     return 0;
  57. }
  58. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment