← All problems

523. Continuous Subarray Sum

MediumOpen on LeetCodeProblem statement

Problem Statement

523. Continuous Subarray Sum

Medium


Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise.

A good subarray is a subarray where:

Note that:

 

Example 1:

Input: nums = [23,2,4,6,7], k = 6
Output: true
Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.

Example 2:

Input: nums = [23,2,6,4,7], k = 6
Output: true
Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.

Example 3:

Input: nums = [23,2,6,4,7], k = 13
Output: false

 

Constraints:

C++

Source file
class Solution {
public:
    bool checkSubarraySum(vector<int>& nums, int k) {
        int running_sum = 0;
        for(int i=0; i<nums.size(); i++)
            nums[i] = running_sum += nums[i];
        unordered_map<int, int> seen;
        // Based on the result that if SUM_JmodK==SUM_ImodK  => (SUM_J-SUM_I)modK==0
        for(int i=0; i<nums.size(); i++){
            int rem = nums[i]%k;
            if(i && !rem)      // base case: contiguous subarray of all array elems upto index i
                return true;
            if(seen[rem]){
                if(i+1-seen[rem]>=2)  // result found
                    return true;
                // else dont update array, cuz it doesnt hurt to find the largest satisfying array
            }
            else seen[rem] = i+1;     // first occurance -> store
        }
        return false;   // not possible
    }
};