Leetcode: Make Sum Divisible by P

Can some one explain me that why we declare m[0]=-1; in below code
Problem link β†’ - LeetCode
code->

class Solution {
public:
int minSubarray(vector& v, int p) {
// vector v(nums.size(),0);
int j= v.size();
unordered_map<int ,int > m;
m[0]=-1;
int req=0;
for(int r=0;r<j;r++){
req= (req+v[r])%p;

    }
    
     if(req==0){
          return 0;
     }
    else
    {
         int ans=j;
        int curr=0;
          for(int e=0;e<j;e++){
              curr=(curr+v[e])%p;
              m[curr]= e;
              int want= (curr +p -req )%p;
               if(m.find( want )!=m.end()){
                   ans= min(e-m[want],ans);
               }
          }
        
        return ans<j?ans:-1;
    }
}

};

First format your code.
Use ``` at start and end of code

This just denotes that prefix sum at index = -1 is 0.
This will be useful to maintain the previous index when subarray to be removed starts from 0 .

You can check this ,You don’t need to declare m[0]=-1.

1 Like