Leetcode 966 Solution

This article provides solution to leetcode question 966 (binary-subarrays-with-sum)

https://leetcode.com/problems/binary-subarrays-with-sum

Solution

class Solution {
public:
    int numSubarraysWithSum(vector<int>& A, int S) {
        unordered_map<int, int> m;
        m[0] = 1;
        int cur = 0;
        int ans = 0;

        for (auto a: A)
        {
            cur += a;
            ans += m[cur - S];
            m[cur]++;
        }

        return ans;
    }
};