Subarray Sum Equals K
Difficulty: Medium
Problem
Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k.
Example
Input: nums = [1, 1, 1], k = 2
Output: 2
Explanation: The subarrays [1,1] (indices 0..1) and [1,1] (indices 1..2) sum to 2.
Brute-force approach
Try every start index and compute sums for every end index.
Steps
- For each start i, initialize sum = 0
- For each end j >= i, add nums[j] to sum
- If sum == k, increment answer
Time complexity: O(n²) · Space complexity: O(1)
Trade-offs
- Too slow for large inputs (n can be up to 20,000)
- Repeatedly recomputes overlapping sums
Optimal approach
Key insight: A subarray ending at index j sums to k if there exists a previous prefix sum equal to (currentPrefix - k).
Maintain a running prefix sum and a hash map of how many times each prefix sum has appeared.
Steps
- Initialize freq[0] = 1 (empty prefix)
- Scan array, updating prefixSum
- Add freq[prefixSum - k] to answer
- Increment freq[prefixSum]
Time complexity: O(n) · Space complexity: O(n)