560. Subarray Sum Equals K
Asked at 40Meta88Microsoft75Amazon74Bloomberg71Google66Apple61Accenture86Yandex80Infosys78Agoda64Visa61Salesforce28AMD79IBM75Sprinklr72Bolt71TikTok71tcs67Grab66Zoho65Cognizant64Capgemini62Quora61Yahoo61Walmart Labs60Nvidia60Palo Alto Networks59ServiceNow55PayPal51EPAM Systems51josh technology50Deloitte50ByteDance50Adobe44Flipkart43Oracle41Goldman Sachs36Capital One35LinkedIn27Uber22
Problem
Count the contiguous, non-empty subarrays of nums whose elements sum to exactly k. Values may be negative.
Example: nums = [1,2,3], k = 3 → 2 ([1,2] and [3])
Constraints: n ≤ 2·10⁴; −1000 ≤ nums[i] ≤ 1000.
Subarray (i, j] sums to k iff pre[j] - pre[i] = k. While scanning, count how many earlier prefixes equal pre - k. Works with negatives (sliding window doesn't).
nums=[1,2,3] k=3 prefix: 0 -> 1 -> 3 -> 6
pre=3: need 0 (seen once) -> +1 [1,2]
pre=6: need 3 (seen once) -> +1 [3] total 2
Complexity: O(n) time, O(n) space.
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
count, pre = 0, 0
seen = defaultdict(int, {0: 1})
for x in nums:
pre += x
count += seen[pre - k]
seen[pre] += 1
return count
assert Solution().subarraySum([1, 1, 1], 2) == 2
assert Solution().subarraySum([1, 2, 3], 3) == 2
assert Solution().subarraySum([1, -1, 0], 0) == 3
class Solution {
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1);
int count = 0, pre = 0;
for (int x : nums) {
pre += x;
count += seen.getOrDefault(pre - k, 0);
seen.merge(pre, 1, Integer::sum);
}
return count;
}
}
func subarraySum(nums []int, k int) int {
count, pre := 0, 0
seen := map[int]int{0: 1} // prefix sum -> how many times seen
for _, x := range nums {
pre += x
count += seen[pre-k]
seen[pre]++
}
return count
}