Algo-Sim › Arrays & Hashing
Subarray Sum Equals K
Medium · Arrays & Hashing · step through it in Java, Python and C++ on your own input
Count the contiguous subarrays whose sum is exactly k, negatives included, with prefix sums and a hash map.
Problem
Given an integer array nums and an integer k, count how many contiguous, non-empty subarrays add up to exactly k.
Constraints
- 1 ≤ nums.length ≤ 2 · 10⁴
- -1000 ≤ nums[i] ≤ 1000
- -10⁷ ≤ k ≤ 10⁷
- Values can be negative, so a sliding window does not work
Edge cases to test
- k = 0
- Negative numbers (why a sliding window fails)
- The whole array sums to k
Follow-up questions
- Why not a sliding window?
- With negatives, growing the window can lower the sum, so there is no rule for when to shrink. Prefix sums with a count map work for any sign: O(n) time and space.
- What if every number is positive?
- Then a sliding window works: shrink while the sum is over k. O(n) time and O(1) space.
- What if you need the longest such subarray instead?
- Store the first index of each prefix sum, and at each i check i − first[sum − k]: O(n).
Solution
Java
public int subarraySum(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
count.put(0, 1);
int prefix = 0, result = 0;
for (int x : nums) {
prefix += x;
result += count.getOrDefault(prefix - k, 0);
count.merge(prefix, 1, Integer::sum);
}
return result;
}Python
def subarray_sum(nums, k):
count = {0: 1}
prefix = result = 0
for x in nums:
prefix += x
result += count.get(prefix - k, 0)
count[prefix] = count.get(prefix, 0) + 1
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int subarraySum(vector<int> &nums, int k) {
unordered_map<int, int> count = {};
count[0] = 1;
int prefix = 0, result = 0;
for (int x : nums) {
prefix += x;
result += (count.count(prefix - k) ? count[prefix - k] : 0);
count[prefix] += 1;
}
return result;
}
};
More Arrays & Hashing problems
- Contains Duplicate (Easy)
- Valid Anagram (Easy)
- Two Sum (Easy)
- Group Anagrams (Medium)
- Top K Frequent Elements (Medium)
- Encode and Decode Strings (Medium)
- Product of Array Except Self (Medium)
- Longest Consecutive Sequence (Medium)
- Majority Element (Easy)
- Find All Numbers Disappeared in an Array (Easy)
- First Missing Positive (Hard)
- Range Sum Query - Immutable (Easy)
- Design HashMap (Easy)