Continuous Subarray Sum in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of non-negative numbers and a target integer k, we have to write a function to check whether the array has a continuous subarray of size at least 2 that sums up to a multiple of k, sums up to n*k where n is also an integer. So if the input is like [23,2,4,6,7], and k = 6, then the result will be True, as [2,4] is a continuous subarray of size 2 and sums up to 6.

To solve this, we will follow these steps −

  • Make a map m, set m[0] := -1 and sum := 0, n := size of nums array
  • for i in range 0 to n – 1
    • sum := sum + nums[i]
    • if k is non zero, then sum := sum mod k
    • if m has sum, and i – m[sum] >= 2, then return true
    • if m does not has sum, set m[sum] := i
  • return false

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool checkSubarraySum(vector<int>& nums, int k) {
      unordered_map<int, int> m;
      m[0] = -1;
      int sum = 0;
      int n = nums.size();
      for(int i = 0; i < n; i++){
         sum += nums[i];
         if(k)
         sum %= k;
         if(m.count(sum) && i - m[sum] >= 2){
            return true;
         }
         if(!m.count(sum)) m[sum] = i;
      }
      return false;
   }
};
main(){
   vector<int> v = {23,2,4,6,7};
   Solution ob;
   cout << (ob.checkSubarraySum(v, 6));
}

Input

[23,2,4,6,7]
6

Output

1
raja
Published on 02-May-2020 13:23:50
Advertisements