Python 0560.py
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
result = 0
found = defaultdict(list)
sum = 0
found[0] = [ -1 ]
for i in range(len(nums)):
sum += nums[i]
found[sum].append(i)
for f in found:
if f + k in found:
for left in found[f]:
right = bisect_right(found[f + k], left)
result += len(found[f + k]) - right
return result
Difficulty
and has an acceptance rate of about 48% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Hash Table
- Prefix Sum
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 classic “subarray sum equals k” problem. It works by first converting the input array into a collection of prefix-sum values together with the positions where each sum occurs. Afterwards it iterates over the distinct prefix sums and, for every pair that differs by k, counts how many index pairs form a valid sub-array. The counting step uses binary search to avoid a quadratic scan, which makes the overall approach considerably faster than a naïve double-loop solution.
Building the prefix-sum map
result = 0
found = defaultdict(list)
sum = 0
found[0] = [ -1 ]
The algorithm starts by creating an empty result counter and a defaultdict named found. The dictionary maps each encountered cumulative sum to a list of indices where that sum appears. Initialising found[0] with [-1] represents the empty prefix before the first element; this entry allows sub-arrays that start at index 0 to be counted correctly.
for i in range(len(nums)):
sum += nums[i]
found[sum].append(i)
During the single pass over nums, the variable sum accumulates the running total. After each addition the current index i is appended to the list associated with the new cumulative sum. By the end of the loop, found contains a complete mapping from every possible prefix sum to all positions where that sum occurs.
Counting matching sub-arrays
for f in found:
if f + k in found:
for left in found[f]:
right = bisect_right(found[f + k], left)
result += len(found[f + k]) - right
The outer loop iterates over each distinct prefix sum f. The inner condition checks whether a complementary sum f + k also exists; only such pairs can produce a sub-array whose elements add up to k.
For every index left where the prefix sum equals f, the code performs a binary search (bisect_right) on the sorted list of indices for f + k. The search returns the insertion point just after the last index that is less than or equal to left. All indices that appear after this insertion point correspond to right-hand boundaries that are strictly greater than left, guaranteeing a non-empty sub-array. The number of those right boundaries is computed as the total length of the list minus the insertion point, and this quantity is added to result.
Edge-case handling
The initialization of found[0] with [-1] ensures that sub-arrays beginning at the first element are correctly recognized. When the input list nums is empty, the first loop does not execute, leaving found with only the entry for sum 0. The subsequent counting loop finds no matching pair, and the function returns 0, which is the correct answer for an empty array.
Negative numbers are naturally accommodated because the cumulative sum can increase or decrease without restriction; the dictionary simply records whatever values appear. The algorithm also works when k is zero. In that situation the condition f + k in found reduces to checking whether the same prefix sum occurs at least twice. The binary-search step then counts all pairs of indices with identical sums, correctly identifying sub-arrays whose total is zero.
Duplicate prefix sums are stored as multiple indices in the same list. Because the lists are built in increasing order of index, they remain sorted, which is a prerequisite for the binary search to function correctly. The use of bisect_right guarantees that sub-arrays of length zero are excluded, as the right boundary must be strictly after the left boundary.
Performance optimizations
The code avoids recomputing prefix sums for every possible sub-array by constructing the found dictionary in a single linear pass. Storing the indices for each sum enables the later counting phase to work with pre-sorted data, eliminating the need for additional sorting steps.
The most significant optimization is the use of binary search (bisect_right) to locate the first viable right boundary for each left index. Without this, the algorithm would need to examine every combination of left and right indices, leading to quadratic work. By leveraging the sorted nature of the index lists, each binary search runs in logarithmic time relative to the size of the list, dramatically reducing the total number of comparisons.
Using a defaultdict(list) eliminates explicit existence checks before appending indices, which streamlines the construction of the prefix-sum map and reduces overhead associated with conditional logic. The overall structure-linear construction followed by a double loop that only performs logarithmic work per iteration-provides a balanced trade-off between memory usage (the dictionary of lists) and speed, especially for inputs containing many repeated prefix sums.
ELI5 - Simplified Explanation
Imagine a long line of numbered building blocks sitting on the floor. Each block has a secret number written on it. This code is like a little robot helper that wants to find every possible group of blocks sitting next to each other that add up to a special goal number called k.
First, the robot clears off a workspace to keep track of the running totals it sees while walking down the line of blocks. It starts by saying that a total of zero has been seen before the very first block.
Next, the robot strolls down the line one block at a time. It keeps a running tally of all the numbers it has passed so far. Each time it gets a new total, it writes that total down along with the spot on the line where it finished counting. This helps the robot remember where all the different amounts are hiding.
Once the robot has finished walking the whole line, it looks at its notes. It checks if there is any place where two different points on the line have a difference that adds up to the special goal number. It matches up the totals it recorded earlier to see if it can jump from one point to another to collect exactly the right amount. If the math works out, it counts that discovery and keeps searching until it has checked every possible combination of blocks.
Code Quality
Complexity Analysis
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++ | Java | Python | TS | |||||||
| WalkCCC | C++ | Java | Python | |||||||||
| leetcode.ca | C++ | Java | Python | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Java | Python | |||||||||
| Progiez | C++ | Java | Python | |||||||||
| github | begeekmyfriend | C | ||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| fsq | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Java | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 523: Continuous Subarray Sum
- problem 713: Subarray Product Less Than K
- problem 724: Find Pivot Index
- problem 974: Subarray Sums Divisible by K
- problem 1658: Minimum Operations to Reduce X to Zero
Solved On The Same Day
- problem 292: Nim Game
- problem 572: Subtree of Another Tree
- problem 617: Merge Two Binary Trees
- problem 671: Second Minimum Node In a Binary Tree
- problem 152: Maximum Product Subarray
- problem 207: Course Schedule
- problem 210: Course Schedule II
- problem 211: Design Add and Search Words Data Structure
- problem 213: House Robber II
- problem 237: Delete Node in a Linked List
- problem 260: Single Number III
- problem 416: Partition Equal Subset Sum
- problem 437: Path Sum III
- problem 450: Delete Node in a BST
- problem 606: Construct String from Binary Tree
- problem 623: Add One Row to Tree
- problem 652: Find Duplicate Subtrees
- problem 654: Maximum Binary Tree
- problem 655: Print Binary Tree
- problem 662: Maximum Width of Binary Tree
- problem 669: Trim a Binary Search Tree
- problem 687: Longest Univalue Path
- problem 1115: Print FooBar Alternately
- problem 1116: Print Zero Even Odd
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