Subarray Sum Equals K
Array, Hash Table
Given an array of integers nums
and an integer k
, return the total number of subarrays whose sum equals to k
.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107
Solutions
Approach - Brute Force Technique
Steps
Initialize Counter: The algorithm starts by initializing a counter
count
to 0. This will keep track of the number of subarrays that sum tok
.Iterate Over Array: The algorithm then enters a nested loop that iterates over each possible subarray in
nums
.Calculate Subarray Sum: For each subarray, the algorithm calculates the sum of the elements in the subarray.
Check for Desired Sum: If the sum of the elements in the subarray equals
k
, the algorithm incrementscount
.
Return Result: After the loops, the algorithm returns
count
, which is the total number of continuous subarrays whose sum equals tok
.
Complexity
Time complexity:
O(N^2)
Space complexity:
O(1)
Approach - Hash Table Technique
Steps
Initialize Variables: The algorithm starts by initializing a dictionary
prefix
to keep track of cumulative sums and their counts, an integersum
to keep track of the cumulative sum, and an integerret
to keep track of the number of subarrays that sum tok
.Handle Base Case: The algorithm adds an entry to the
prefix
dictionary for a sum of zero with a count of one. This represents the sum of no elements.Iterate Over Array: The algorithm then enters a loop that iterates over each element in the input array
nums
.Update Cumulative Sum: For each element, the algorithm adds the element’s value to
sum
.Check for Subarray Sum: The algorithm calculates the value
find
as the difference between the current cumulative sum andk
. Iffind
is in theprefix
dictionary, it means that there is a subarray ending at the current index with a sum ofk
. The algorithm incrementsret
by the count offind
inprefix
.Update Prefix Dictionary: The algorithm then checks if the current cumulative sum is in the
prefix
dictionary. If it is, the count is incremented; otherwise, a new entry is added with a count of one.
Return Result: After the loop, the algorithm returns
ret
, which is the total number of continuous subarrays whose sum equals tok
.
Complexity
Time complexity:
O(N)
Space complexity:
O(N)
Last updated