Javascript O(n). Prefix Sum & HashMap with Explanation
Let me explain this line: let prevSum = mod(sum-total,p).\nThe idea is as follows:\nThe question wnats us to find sum of some subarray such that (total - sum of
Let me explain this line: `let prevSum = mod(sum-total,p)`.\nThe idea is as follows:\nThe question wnats us to find sum of some subarray such that `(total - sum of some subarray) % p`  will be 0.\n\nThis implies that `(total - (sum[i] - sum[j]))%p = 0`. Where `sum[i]` = `nums[0] + nums[1] + ... nums[i]`  and `j<=i`\nSo `sum[i] - sum[j]` is the range sum of nums after index `j` to index `i`\n\nNow, `(total - (sum[i] - sum[j]))%p = 0`\n\nis same as `(total%p  - sum[i]%p  + sum[j]%p))%p = 0`\n\nso, `total%p  - sum[i]%p  + sum[j] %p = 0`\n\n`sum[j]%p =  sum[i]%p -total %p `. Recall that `j <= i`, this means that `\'sum[j]%p` is a previous sum we\'ve already compututed and stored in the map. So whenever the current sum - total evaluates to a previous sum we have already seen, then it means that range is a candidate length. \n\nIn other words:\n`(total - (sum[i] - sum[j]))%p = 0` can be expressed as `sum[j]%p =  sum[i]%p -total %p `. I use the `mod` function to help evaluate negative values correctly.\n\n```\nvar minSubarray = function(nums, p) {\n    let n = nums.length;\n    let map = new Map([[0,-1]])\n    let total = 0, res = n, sum = 0\n    for(let i=0; i<n; i++){\n        total += nums[i]\n    }\n    total = total % p\n    \n    for(let i=0; i<n; i++){\n        sum = (sum + nums[i]) % p\n        map.set(sum, i)\n        let prevSum = mod(sum-total,p)\n        if(map.has(prevSum)){\n            res = Math.min(res, i-map.get(prevSum))\n        }\n    }\n\n    return res == nums.length ? -1 : res\n};\n\nfunction mod(a,b){\n    let c = a%b\n    return c<0 ? c+b : c\n}\n```
['JavaScript']