Intuition
- Difference between this one and Minimum Size Subarray Sum is this one asks for exactly = k and the other one is k, and also Minimum Size Subarray Sum has only positive numbers which makes all the difference.
- Sliding Window doesn’t work because we have negative numbers, and so that messes up our calculation along with [1] and k = 0, since cur_sum would have reset to 0 by this point.
- Note that it has to be cur_sum - k, NOT k - cur_sum, since you are getting a negative number and you wish to see if
Complexity
Runtime
Space
Code
TLE
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
res = 0
n = len(nums)
for starting_point in range(n):
cur_sum = 0
for j in range(starting_point, n):
cur_sum += nums[j]
if cur_sum == k:
res += 1
return resNotes
Cards
START Basic Front: Subarray Sum Equals K Back:
END