Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Mohammed Dh Abbas
sliding window solution. O(1) space

Mohammed Dh Abbas

Aug 18, 2024

class Solution: def numSubarraysWithSum(self, nums, goal): count = 0 j = 0 add = 0 for i in range(len(nums)): add += nums[i] # move j only if add becomes larger than goal 0 while add > goal: add -= nums[j] j += 1 if add == goal: count += 1 # without prefix 0 # j wont move but we want to count all the prefix 0 . # like 0 0 1 1 goal 2 answer = 3 k = j while nums[k] == 0: count += 1 k += 1 return count

0

0

Comments
Comments

On this page