Subarray Sum Equals K in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers and an integer k, we need to find the total number of continuous subarrays whose sum same as k. So if nums array is [1, 1, 1] and k is 2, then the output will be 2.

To solve this, we will follow these steps −

  • define one map called sums, temp := 0, sums[0] := 1 and ans := 0
  • for i in range 0 to size of the array
    • temp := temp + n[i]
    • if sums has k – temp, then
      • ans := ans + sums[k - temp]
    • increase the value of sums[-temp] by 1
  • return ans

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int subarraySum(vector<int>& n, int k) {
      unordered_map <int, int> sums;
      int temp = 0;
      sums[0] = 1;
      int ans =0;
      for(int i =0;i<n.size();i++){
         temp+= n[i];
         if(sums.find(k-temp)!=sums.end()){
            ans += sums[k-temp];
         }
         sums[-temp]++;
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,1};
   cout << (ob.subarraySum(v, 2));
}

Input

[1,1,1]
2

Output

2
raja
Published on 27-Feb-2020 10:14:25
Advertisements