Python 0930.py
class Solution:
def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:
result = 0
prefix = defaultdict(int)
prefix[0] = 1
total = 0
for n in nums:
total += n
result += prefix[total - goal]
prefix[total] += 1
return result
Difficulty
and has an acceptance rate of about 70% (800k+ submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Prefix Sum
- Sliding Window
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of counting subarrays whose elements sum to a specified target (goal). It does so by converting the subarray-sum requirement into a prefix-sum difference problem and then using a hash map to record how many times each prefix sum has occurred. By scanning the input list once, the algorithm accumulates the answer in the variable result.
Key Steps
Initialization of Counters
result = 0
prefix = defaultdict(int)
prefix[0] = 1
total = 0
The variable result holds the final count.
prefix is a dictionary that maps each encountered prefix sum to the number of times it has appeared; it is seeded with a count of one for the sum 0 to correctly handle subarrays that start at index 0.
total tracks the running prefix sum as the array is traversed.
Single-Pass Traversal
for n in nums:
total += n
result += prefix[total - goal]
prefix[total] += 1
During each iteration the current element n is added to total, producing the prefix sum up to the current index.
The expression total - goal represents the prefix sum that must have occurred earlier for the segment between that earlier index and the current one to sum to goal. The dictionary lookup prefix[total - goal] yields the number of such earlier occurrences, which is added to result.
Finally, the current prefix sum total is recorded in prefix for future iterations.
Return of the Computed Count
return result
After processing all elements, result contains the total number of subarrays whose sum equals goal.
Edge Cases Handled
The algorithm gracefully manages several boundary conditions without additional code. When the input list nums is empty, the loop body never executes; result remains zero, which is the correct answer because no subarrays exist. If goal is zero, the lookup prefix[total - goal] simplifies to prefix[total], counting subarrays whose sum is zero, including those formed by consecutive zeros or by a single zero element. The initial entry prefix[0] = 1 ensures that a subarray starting at the first element and directly achieving the target is counted, because the required previous prefix sum of zero is already present.
Performance Optimizations
The solution achieves linear time performance by processing each element exactly once and performing only constant-time dictionary operations per iteration. The use of defaultdict(int) eliminates the need for explicit existence checks before incrementing counts, reducing overhead. Memory usage grows proportionally to the number of distinct prefix sums encountered; in the worst case this is bounded by the length of the input array, but the structure remains a simple hash map without auxiliary data structures. The direct accumulation into result avoids the need for a secondary pass or additional storage for intermediate subarray indices.
ELI5 - Simplified Explanation
Imagine having a long train track made of blocks, where some blocks have a number on them and others are empty. The goal is to figure out how many different sections of this track add up to a specific magic number.
First, set up a special notebook to keep track of the sums seen along the way. Think of this notebook as a way to remember how many times a certain sum has happened before reaching the current spot. Start by writing down that a sum of zero has happened one time.
Then, walk down the track block by block. As each block is passed, add the number on that block to a running total. This running total tells the current height of the stack of pieces collected so far.
After updating the total, check the notebook to see if the current total minus the magic number has appeared before. If it has, that means a piece of the track somewhere behind matches the target goal. Keep track of these matches by counting them up as the walk continues.
Finally, every time a total is calculated, update the notebook by making a mark to show that this specific total has been reached one more time. By the time the end of the track is reached, the counting part is done.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | JS | Java | Go | |||
| LeetcodeHelp | C++ | Python | Java | |||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 2302: Count Subarrays With Score Less Than K
- problem 2489: Number of Substrings With Fixed Ratio
- problem 2750: Ways to Split Array Into Good Subarrays
- problem 3129: Find All Possible Stable Binary Arrays I
- problem 3130: Find All Possible Stable Binary Arrays II
Solved On The Same Day
- problem 1190: Reverse Substrings Between Each Pair of Parentheses
- problem 1219: Path with Maximum Gold
- problem 446: Arithmetic Slices II - Subsequence
- problem 1235: Maximum Profit in Job Scheduling
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality