Problem 930

Abstract / Summary

Count the number of continuous groups of 0s and 1s that together contain exactly one 1.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
14 lines | 339 bytes | submitted January 7, 2024 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 70% (800k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Hash Table
  • Prefix Sum
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 9 | μ = 8.52 | σ = 0.92

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
28 links | 15 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

5 similar problems

Solved On The Same Day

5 solutions   January 7, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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