Algorithm-Day10-Subarray-Sum-Equals-K-lc-560
🧩 Problem Description
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
💡 Brute Force (Too Slow)
Try every subarray and compute its sum.
1 | // Time: O(n^2) |
- ❌ Time complexity: O(n²)
- Works only for small inputs
💡 Optimized Approach: Prefix Sum + HashMap
✨ Key Insight
If we know the prefix sum up to index i
is sum
, and we previously saw a prefix sum of sum - k
,
then the subarray between those two indices sums to k
.
✅ Steps
- Use a
Map<Integer, Integer>
to count how many times each prefix sum has occurred. - At each step:
- Add current number to running sum
- Check if
sum - k
has appeared before → it means a subarray with sum = k ends here - Add
sum
to the map
🔢 Java Code
1 | class Solution { |
⏱ Time and Space Complexity
- Time Complexity: O(n)
One pass through the array - Space Complexity: O(n)
For the prefix sum map
✍️ Summary
- Prefix sum is a powerful technique for cumulative problems
- The hash map tracks all possible sums we’ve seen so far
- Key trick: initialize the map with
{0:1}
to handle cases where subarray starts at index 0
This is a high-frequency interview question and a foundation for other problems like
Longest Subarray Sum
,Count of Subarrays With Sum Divisible by K
, etc.