DEV Community

Karleb
Karleb

Posted on

#523. Continuous Subarray Sum

https://leetcode.com/problems/continuous-subarray-sum/description/?envType=daily-question&envId=2024-06-11


js

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {boolean}
 */
var checkSubarraySum = function(nums, k) {
    let sum = 0
    const remainderMap = new Map()
    remainderMap.set(0, -1)

    for(let i = 0; i < nums.length; i++) {
        sum += nums[i]

        let remainder = sum % k

        remainder = remainder < 0 ? remainder + k : remainder

        if (remainderMap.has(remainder)) {
            if (i - remainderMap.get(remainder) > 1) return true
        } else {
            remainderMap.set(remainder, i)
        }
    }

    return false
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)