Skip to content

Commit bce1109

Browse files
committed
Sync LeetCode submission Runtime - 34 ms (40.18%), Memory - 18.6 MB (52.61%)
1 parent b56f88e commit bce1109

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed
Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,28 @@
1-
# Approach 1: Prefix Sum
1+
# Approach 2: Sliding Window
22

33
# Time: O(n)
4-
# Space: O(n)
4+
# Space: O(1)
55

66
class Solution:
7-
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
8-
total_count = 0
9-
curr_sum = 0
10-
sum_freq = {0 : 1} # {prefix_sum : frequency}
7+
# Helper function to count the number of subarrays with sum at most the given goal
8+
def sliding_window_at_most(self, nums: List[int], goal: int) -> int:
9+
start, curr_sum, total_count = 0, 0, 0
10+
11+
for end in range(len(nums)):
12+
curr_sum += nums[end]
1113

12-
for num in nums:
13-
curr_sum += num
14-
if curr_sum - goal in sum_freq:
15-
total_count += sum_freq[curr_sum - goal]
16-
17-
sum_freq[curr_sum] = sum_freq.get(curr_sum, 0) + 1
14+
# Adjust the window by moving the start pointer to the right
15+
# until the sum becomes less than or equal to the goal
16+
while start <= end and curr_sum > goal:
17+
curr_sum -= nums[start]
18+
start += 1
19+
20+
# Update the total count by adding the length of the current subarray
21+
total_count += end - start + 1
1822

1923
return total_count
2024

2125

26+
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
27+
return self.sliding_window_at_most(nums, goal) - self.sliding_window_at_most(nums, goal - 1)
2228

0 commit comments

Comments
 (0)