C++ Hashmap to check partial sum mod k


  • 0
        bool checkSubarraySum(vector<int>& nums, int k) {
            if (!k) {
                for (int i = 0; i < nums.size()-1; ++i)
                  if (!nums[i] and !nums[i+1]) return true;   
    
                return false;
            }
            
            if (k < 0) k = -k;
            unordered_map<int, int> modk2idx; modk2idx[0] = -1;
            for (int i = 0, sum = 0; i < nums.size(); ++i) {
                int mod = (sum += nums[i])%k; 
                if (modk2idx.count(mod)) {
                    if (i - modk2idx[mod] > 1) return true;
                }
                else modk2idx[mod] = i;
            }
            return false;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.