<jupyter_start><jupyter_text>https://leetcode.com/problems/subarray-sum-equals-k/ Other solutions: https://leetcode.com/problems/subarray-sum-equals-k/discuss/503178/Python5-Approaches-easy-to-understand-with-detailed-explanations<jupyter_code># Brute force (time limit in leetcode is exceeded)

def subarraySum(nums, k: int) -> int:
    cnt = 0
    for i in range(len(nums)):
        for j in range(i+1,len(nums)+1):
            if sum(nums[i:j]) == k:
                cnt += 1
    return cnt

subarraySum([1,1,1],2)<jupyter_output><empty_output><jupyter_text>Note: this solution only works for an array (nums) of positive numbers.<jupyter_code># Sliding Window
class Solution:
    def subarraySum(self, nums, k: int) -> int:
        def isneg(x):
            return abs(x)!=x
        n = len(nums)
        l,r = 0,0
        res = 0
        rs = 0
        while l < n:
            keep_going = False
            while rs <= k or keep_going:
                if r >= n:
                    break
                rs += nums[r]
                if isneg(nums[r]):
                    keep_going = True
                r+=1
                print("right",rs,nums[l:r])
                if rs == k and r-l > 0:
                    res += 1
            while r >= n or rs >= k:
                if l>=n:
                    break
                rs -= nums[l]
                l+=1
                print("left",rs,nums[l:r])
                if rs == k and r-l > 0:
                    res+=1
        return res<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup