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.

  1. Track sum and a count.
  2. Use an Object map where map[sum] = frequency. Initialize map[0] = 1.
  3. For each num:
    • Add to sum.
    • If map[sum - k] exists, add that frequency to count.
    • Update map[sum].
  4. Print the final count.

01EXAMPLE 1

Inputnums=[1, 1, 1], k=2
Output2

Explanation: [1,1] and [1,1].

Constraints

  • Solve in O(n) time using Hashing.
ArraysPrefix SumHashing
JavaScript
Loading...
1 Hidden

Input Arguments

nums[1,1,1]
k2

Expected Output

2

Click RUN to test your solution