Subarray Sum Equals K - Prefix Sum Pattern
Subarray Sum Equals K in Java using the Prefix Sum pattern: problem statement, approach, template, complexity, and interview tips.
Subarray Sum Equals K
Problem Statement
Given an integer array nums and an integer k, return the number of contiguous subarrays whose sum equals k.
Pattern: Prefix Sum
Precompute running totals so any range sum can be answered in constant time, and so equal-sum questions become hash-map lookups.
Use this pattern when the problem asks about sums of subarrays or ranges, or about counting subarrays with a given sum.
Approach
- Build a prefix array (or running sum) in one pass.
- Express the answer as a difference of two prefix values.
- Use a hash map of prefix value to count or first index when you need to find matching earlier prefixes.
Pattern Template (Java)
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + nums[i];
}
// sum of nums[l..r] = prefix[r + 1] - prefix[l]
Adapt this template to the exact rules of Subarray Sum Equals K: decide what state you track, what condition moves the loop forward, and what the final answer is.
Complexity
O(n) time and O(n) space is typical.
Interview Tips
- Watch the off-by-one between array indices and prefix indices.
- Seed the hash map with prefix 0 so subarrays starting at index 0 are counted.
- Start with a brute-force idea, state its complexity, then explain how the Prefix Sum pattern improves it.
- Walk through a small example and at least one edge case (empty input, a single element, duplicates).
Related Problems
Continue Learning
Parent: DSA Interview Learning Path | Previous: Range Sum Query Immutable | Next: Contiguous Array
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.