KatInterview

966. Binary Subarrays With Sum

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method Explanation

The problem asks for the number of contiguous subarrays with a specific sum, goal. A naive approach of checking every possible subarray would be O(n²), which is too slow given the constraints (n <= 30,000). A more efficient O(n) approach is needed.

Solution

Binary Subarrays With Sum in Python

class Solution:
    def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
        # Use a hash map (dictionary) to store the frequency of prefix sums.
        # collections.defaultdict is convenient to avoid checking for key existence.
        prefix_sum_count = collections.defaultdict(int)
        
        # Initialize with prefix sum 0 having occurred once.
        # This handles subarrays that start from index 0.
        prefix_sum_count[0] = 1
        
        current_sum = 0
        total_count = 0
        
        for num in nums:
            # Update the current running prefix sum.
            current_sum += num
            
            # We are looking for a previous prefix sum `prev_sum` such that:
            # current_sum - prev_sum = goal
            # This means prev_sum = current_sum - goal.
            # We check our map to see how many times `current_sum - goal` has occurred.
            needed_sum = current_sum - goal
            if needed_sum in prefix_sum_count:
                total_count += prefix_sum_count[needed_sum]
            
            # Increment the count for the current prefix sum in the map.
            prefix_sum_count[current_sum] += 1
            
        return total_count

Binary Subarrays With Sum in Java

class Solution {
    public int numSubarraysWithSum(int[] nums, int goal) {
        // Use a hash map to store the frequency of prefix sums.
        // Key: prefix sum, Value: frequency
        Map<Integer, Integer> prefixSumCount = new HashMap<>();
        
        // Initialize with prefix sum 0 having occurred once.
        // This handles subarrays that start from index 0.
        prefixSumCount.put(0, 1);
        
        int currentSum = 0;
        int totalCount = 0;
        
        for (int num : nums) {
            // Update the current running prefix sum.
            currentSum += num;
            
            // We are looking for a previous prefix sum `prevSum` such that:
            // currentSum - prevSum = goal
            // This means prevSum = currentSum - goal.
            // We check our map for the count of `currentSum - goal`.
            int neededSum = currentSum - goal;
            totalCount += prefixSumCount.getOrDefault(neededSum, 0);
            
            // Increment the count for the current prefix sum in the map.
            prefixSumCount.put(currentSum, prefixSumCount.getOrDefault(currentSum, 0) + 1);
        }
        
        return totalCount;
    }
}

Binary Subarrays With Sum in C++

class Solution {
public:
    int numSubarraysWithSum(vector<int>& nums, int goal) {
        // Use a hash map to store the frequency of prefix sums.
        // Key: prefix sum, Value: frequency
        std::unordered_map<int, int> prefixSumCount;
        
        // Initialize with prefix sum 0 having occurred once.
        // This handles subarrays that start from index 0.
        prefixSumCount[0] = 1;
        
        int currentSum = 0;
        int totalCount = 0;
        
        for (int num : nums) {
            // Update the current running prefix sum.
            currentSum += num;
            
            // We are looking for a previous prefix sum `prevSum` such that:
            // currentSum - prevSum = goal
            // This means prevSum = currentSum - goal.
            // We check our map to see how many times `currentSum - goal` has occurred.
            int neededSum = currentSum - goal;
            if (prefixSumCount.count(neededSum)) {
                totalCount += prefixSumCount[neededSum];
            }
            
            // Increment the count for the current prefix sum in the map.
            prefixSumCount[currentSum]++;
        }
        
        return totalCount;
    }
};

Binary Subarrays With Sum in TypeScript

function numSubarraysWithSum(nums: number[], goal: number): number {
    // Use a Map to store the frequency of prefix sums.
    // Key: prefix sum, Value: frequency
    const prefixSumCount = new Map<number, number>();
    
    // Initialize with prefix sum 0 having occurred once.
    // This handles subarrays that start from index 0.
    prefixSumCount.set(0, 1);
    
    let currentSum = 0;
    let totalCount = 0;
    
    for (const num of nums) {
        // Update the current running prefix sum.
        currentSum += num;
        
        // We are looking for a previous prefix sum `prevSum` such that:
        // currentSum - prevSum = goal
        // This means prevSum = currentSum - goal.
        // We check our map for the count of `currentSum - goal`.
        const neededSum = currentSum - goal;
        if (prefixSumCount.has(neededSum)) {
            totalCount += prefixSumCount.get(neededSum)!;
        }
        
        // Increment the count for the current prefix sum in the map.
        prefixSumCount.set(currentSum, (prefixSumCount.get(currentSum) || 0) + 1);
    }
    
    return totalCount;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.