Subarray Sum Pulse
HardAcc. 72.4%
+50 XP 25
Target Range Hashing
If CurrentSum - K was seen as a previous Prefix Sum, then a subarray with sum K exists between that point and the current index.
The Assignment
Your function receives nums and k.
- Track
sumand acount. - Use an Object
mapwhere map[sum] = frequency. Initialize map[0] = 1. - For each num:
- Add to
sum. - If
map[sum - k]exists, add that frequency tocount. - Update
map[sum].
- Add to
- Print the final
count.
01EXAMPLE 1
Input
nums=[1, 1, 1], k=2Output
2Explanation: [1,1] and [1,1].
Constraints
- Solve in O(n) time using Hashing.
ArraysPrefix SumHashing
JavaScriptSystem handles I/O — write your function only
Loading...
1 Hidden
Input Arguments
nums[1,1,1]
k2
Expected Output
2
Click RUN to test your solution