Advertisement
smj007

Subarray sum equals k (only positive integers)

Apr 24th, 2025
325
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.65 KB | None | 0 0
  1. class Solution:
  2.     def subarraySum(self, nums: List[int], k: int) -> int:
  3.  
  4.         left = 0
  5.         right = 0
  6.         window_sum = 0
  7.         count = 0
  8.  
  9.         while right < len(nums):
  10.            
  11.             # add the right to the window
  12.             window_sum += nums[right]
  13.  
  14.             # shrink the window untill we have sum < k
  15.             while window_sum > k:
  16.                 window_sum -= nums[left]
  17.                 left += 1
  18.  
  19.             # if current window has sum equal to k
  20.             if window_sum == k:
  21.                 count += 1
  22.            
  23.             # expand the window
  24.             right += 1
  25.  
  26.         return count
  27.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement