560. Subarray Sum Equals K
Intitution
To find the number of subarrays whose sum is equal to k
, we can use the concept of prefix sums.
If the sum of elements from index i
to j
is k
, then:
Rearranging:
So, for each prefix sum encountered, we want to know how many times (currentPrefixSum - k)
has appeared before.
This is efficiently done using a hash map to track prefix sum frequencies.
Complexity
Space Complexity
Time Complexity
Code
Last updated