24. Subarray Sum Equals K
mediumAsked at DatabricksCount contiguous subarrays whose values sum to k — the prefix-sum technique here is the same one Databricks uses to compute rolling aggregations over unbounded streaming windows in Structured Streaming.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals k.
Constraints
1 <= nums.length <= 2 * 10^4-1000 <= nums[i] <= 1000-10^7 <= k <= 10^7
Examples
Example 1
nums = [1,1,1], k = 22Explanation: Subarrays [1,1] at indices 0-1 and 1-2 both sum to 2.
Example 2
nums = [1,2,3], k = 32Explanation: [1,2] and [3] each sum to 3.
Approaches
1. Brute force — all subarrays
For each pair (i, j), compute the subarray sum and compare to k. O(n^2) time — impractical for large streaming windows.
- Time
- O(n^2)
- Space
- O(1)
function subarraySum(nums, k) {
let count = 0;
for (let i = 0; i < nums.length; i++) {
let sum = 0;
for (let j = i; j < nums.length; j++) {
sum += nums[j];
if (sum === k) count++;
}
}
return count;
}Tradeoff:
2. Prefix sum with hash map
Maintain a running prefix sum and a map from sum → count of times seen. For each position, the number of valid subarrays ending here equals the count of earlier prefix sums equal to (currentSum - k).
- Time
- O(n)
- Space
- O(n)
function subarraySum(nums, k) {
const prefixCount = new Map([[0, 1]]);
let sum = 0, count = 0;
for (const num of nums) {
sum += num;
count += prefixCount.get(sum - k) || 0;
prefixCount.set(sum, (prefixCount.get(sum) || 0) + 1);
}
return count;
}Tradeoff:
Databricks-specific tips
This problem is a frequent Databricks phone screen fixture because it tests prefix-sum intuition — a building block of their Photon query engine's aggregate operators. Emphasize that the map must be seeded with {0: 1} before processing: without it, subarrays starting at index 0 are missed. Interviewers will ask a follow-up about negative numbers — the prefix-sum approach handles them correctly, unlike a sliding-window approach, so address that proactively.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Subarray Sum Equals K and other Databricks interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →