Subarray Sum Equals K

Problem

Given an array of integers and a target k, find the total number of contiguous subarrays whose sum equals k.

Input:  nums = [1, 1, 1], k = 2
Output: 2

Python Solution

def subarray_sum(nums, k):
    count = 0
    prefix_sum = 0
    seen = {0: 1}
    for num in nums:
        prefix_sum += num
        count += seen.get(prefix_sum - k, 0)
        seen[prefix_sum] = seen.get(prefix_sum, 0) + 1
    return count

C++ Solution

int subarraySum(vector<int>& nums, int k) {
    int count = 0, prefixSum = 0;
    unordered_map<int, int> seen;
    seen[0] = 1;
    for (int num : nums) {
        prefixSum += num;
        if (seen.count(prefixSum - k)) count += seen[prefixSum - k];
        seen[prefixSum]++;
    }
    return count;
}

Java Solution

class Solution {
    public int subarraySum(int[] nums, int k) {
        int count = 0, prefixSum = 0;
        Map<Integer, Integer> seen = new HashMap<>();
        seen.put(0, 1);
        for (int num : nums) {
            prefixSum += num;
            count += seen.getOrDefault(prefixSum - k, 0);
            seen.put(prefixSum, seen.getOrDefault(prefixSum, 0) + 1);
        }
        return count;
    }
}

Complexity

Time: O(n) — one pass, with O(1) average hash map lookups and updates. Space: O(n) — the hash map can store up to n distinct prefix sums.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.