Description
Given an array of integers and an integer k
, you need to find the total number of continuous subarrays whose sum equals k
.
Example 1:
1 | Input: nums = [1,1,1], k = 2 |
Solution
We can use the prefix sum technique to solve the problem. Instead of calculating the sum of all possible subarrays(O(n) each
), we can use the prefix sums to get the sum of subarray (i, j)
in O(n)
. Now we just have to iterate through all (i, j)
pairs and count how many sums are equal to k
. The total time complexity is O(n^2)
.
Optimization
We can do better. Iterating through all (i, j)
pairs is expensive. We can instead use a dict
to store the number of each specific prefix sum. Since we want prefix[i]-prefix[j] = k
, we can easily know how many j
s are valid, by finding the numbers of prefix sums that are k-prefix[j]
in dict
. To avoid counting duplicates, we calculate the prefix sums along with the counting process. The time complexity is now O(n)
.
Here is my code:
1 | from collections import defaultdict |