Tensorum
LeetCode 930 · Counting Subarrays (Exactly K = AtMost K − AtMost K−1)

Binary Subarrays With Sum

LeetCode 930 · Medium · solution, intuition & step-by-step walkthrough

exactly(k) = atMost(k) − atMost(k − 1).

MediumArrayHash TableSliding WindowPrefix Sum
58 msruntime · beats 7%
51.9 MBmemory · beats 100%
1approach
4accepted runs · last 5 May 2024

This is how I solved Binary Subarrays With Sum (LeetCode 930), a medium problem from the Counting Subarrays (Exactly K = AtMost K − AtMost K−1) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Counting windows with sum exactly goal is awkward, but counting windows with sum ≤ goal is easy with a sliding window (each right edge adds r − l + 1 windows). Exactly goal = atMost(goal) − atMost(goal − 1).

Approach

  1. 1

    atMost(goal): expand right, shrink while the sum exceeds goal.

  2. 2

    Every right edge contributes r − l + 1 subarrays.

  3. 3

    Return atMost(goal) − atMost(goal − 1).

  4. 4

    An earlier version used prefix sums with a hash map.

How I solved it

atMost(k) − atMost(k−1)PythonO(n) time · O(1) space
class Solution:
    def getCountSubArray(self, nums, goal):
        if goal < 0:
            return 0
        cnt = 0
        total = 0
        l = 0
        for r in range(len(nums)):
            total += nums[r]
            while total > goal:
                total = total - nums[l]
                l += 1
            if total <= goal:
                cnt += r - l + 1
        return cnt

    def numSubarraysWithSum(self, nums, goal):
        return self.getCountSubArray(nums, goal) - self.getCountSubArray(nums, goal - 1)
Loading the step-through…

Binary Subarrays With Sum — FAQ

What is the intuition behind Binary Subarrays With Sum?

Counting windows with sum exactly goal is awkward, but counting windows with sum ≤ goal is easy with a sliding window (each right edge adds r − l + 1 windows). Exactly goal = atMost(goal) − atMost(goal − 1).

How do you solve Binary Subarrays With Sum (LeetCode 930)?

1. atMost(goal): expand right, shrink while the sum exceeds goal. 2. Every right edge contributes r − l + 1 subarrays. 3. Return atMost(goal) − atMost(goal − 1). 4. An earlier version used prefix sums with a hash map.

What is the time and space complexity of Binary Subarrays With Sum?

Time: O(n). Space: O(1). (Accepted approach: atMost(k) − atMost(k−1).)

What are common mistakes in Binary Subarrays With Sum?

atMost(−1) must return 0.