C++ faster than 96% submissions
logic is pretty simple....it is just that you should have intuition of modulo operator i.e. it gives us the extra value which is present in our number e.g. 7%4=
logic is pretty simple....it is just that you should have intuition of modulo operator i.e. it gives us the extra value which is present in our number e.g. 7%4=3 so 3 is extra in 7.\n\nsimilarly when we calculate sum of array and do its modulo with p then it gives us extra value which is present in sum.\n\nso basically our objective is to find a subarray whose sum_subarray%p==sum_array%p.\n\nbrute force solution can be to generate all subarrays find their sum, do modulo and get minimum length subarray....which will take O(n2) time and O(1) space.(TLE)\n\nlet\'s go to optimise solution(in terms of time)\ntarget=sum_whole_array%p;\nwe are looking for subarray whose sum_subarray%p==target or we can say s(i,j)%p==target or \n(f(j)-f(i)) %p==target or (f(j)%p -f(i)%p)%p==target....note that since f(j)%p-f(i)%p can be negative hence we have to do (f(j)%p -f(i)%p + p)%p ==target......INTUITION IS.... extra  value till jth index - extra value till ith index == target....j>i \nor we are just assuming that there is a subarray ending with jth index whose sum%p==target...and if this is so then there must be a subarray ending with ith index such that \nextra  value till jth index - extra value till ith index == target....j>i ...i.e....(f(j)%p -f(i)%p + p)%p ==target\nso for find that we will use hashmap.\n\n\n```\nclass Solution {\npublic:\n    int minSubarray(vector<int>& nums, int p) {\n       int n=nums.size();\n       long long sum=0;\n        for(int i=0;i<n;i++)\n        {\n           sum+=nums[i]; \n        }\n       \n        if(sum%p==0)return 0;\n\t\t int ans=INT_MAX;\n        int target=sum%p;\n        unordered_map<int,int>m;//key is modulo and element is index\n        sum=0;\n        m[0]=-1;\n        for(int i=0;i<n;i++)\n        {\n           sum+=nums[i];\n            m[sum%p]=i;\n            if(m.find((sum%p-target+p)%p)!=m.end())\n            {\n                int j=m[(sum%p-target+p)%p];\n                ans=min(ans,i-j);\n            }\n        }\n        if(ans==INT_MAX || ans==nums.size())\n            return -1;\n        return ans;\n    }\n};
['C']