Hi👋SpeedAlgo • Deliberate Practice & Cognitive Ergonomics for Software Engineers

An interactive algorithm mastery and technical interview preparation platform published by Hi👋WebEnterprise. Built for senior and staff software engineers preparing for rigorous coding screens at top tech companies (FAANG/MAMAA).

12 Core Algorithmic Patterns & 189 Practice Problems

  • 1. Two Pointers (10 Paradigms, 34 Problems): Converging pointers, sorted pair sums, container with most water, trapping rain water, 3Sum, plus the Sliding Window and Fast & Slow Pointers paradigms (Floyd cycle detection, monotonic window invariants, longest substrings, minimum window).
  • 2. Binary Search (8 Paradigms, 12 Problems): Monotonic predicate partitioning, boundary searching, rotated arrays, median of two sorted arrays, matrix median on value range.
  • 3. Bit Manipulation (5 Paradigms, 8 Problems): Bitmasking, XOR tricks, counting set bits, subset enumeration via bitmasks.
  • 4. Math & Geometry (7 Paradigms, 13 Problems): Sieve of Eratosthenes, integer/roman conversions, modular arithmetic, geometric simulation.
  • 5. Tree/Graph Depth-First Search (10 Paradigms, 19 Problems): Path sums, lowest common ancestor, tree diameter, subtree serialization, validating BSTs.
  • 6. Tree/Graph Breadth-First Search (4 Paradigms, 11 Problems): Level-order traversals, shortest path, rotting oranges, word ladders.
  • 7. Graphs (10 Paradigms, 18 Problems): Topological sort, cycle detection, Dijkstra, bipartite validation, network delay.
  • 8. Backtracking (6 Paradigms, 14 Problems): Subsets, permutations, combinations, constraint satisfaction, pruning, N-Queens.
  • 9. Dynamic Programming (11 Paradigms, 18 Problems): Memoization vs tabulation, knapsack, coin change, edit distance, longest common subsequence.
  • 10. Heap / Priority Queue (8 Paradigms, 10 Problems): Running medians, top-k elements, interval scheduling, IPO, k-way merges.
  • 11. Advanced Data Structures (6 Paradigms, 14 Problems): Trie, Union-Find, LRU Cache, LFU Cache, Monotonic Stacks.
  • 12. Intervals & Stack / Miscellaneous (11 Paradigms, 18 Problems): Merge intervals, daily temperatures, largest rectangle in histogram, trapping rain water via stack.

4-Stage Deliberate Practice Framework

  1. Stage 1 (Compare & Learn): Multi-language Rosetta Stone contrasting abstract invariants with concrete solutions across Python, C#, Java, TypeScript, C++, Go, and Rust.
  2. Stage 2 (Active Recall): Reconstruct algorithmic template invariants from memory with real-time feedback before looking at solutions.
  3. Stage 3 (Senior SWE AI Mock Coach): Simulated senior mock interview evaluating Big-O space/time tradeoffs, edge cases, and code reviews in Monaco Editor.
  4. Stage 4 (Solve on Your Own): Timed sandbox challenges verified against automated test suites in Python, C#, Java, and TypeScript.

Equipped with SM-2 Spaced Repetition Review Hub, Studio Cockpit workspace layout, and interactive study notes.

Pricing, Access & Commercial Terms

  • Core Curriculum: 100% Free. No credit card required.
  • Compute Coins: 40 free coins upon signup, +20 daily login bonus, +25 referral bonus.
  • 24-Hour AI Coaching Pass: 5 compute coins unlocks unlimited senior SWE AI coaching for a full 24 hours.
  • BYOK (Bring Your Own Key): Completely free unlimited AI coaching if using your own Gemini/OpenAI API key.
  • Refund & Subscription Policy: No recurring charges, no subscription traps, and no paid paywalls. Free tier provides full learning path.
  • Platform Operator: Hi👋WebEnterprise Inc. Support & policies at hispeedalgo.com.
Skip to main content
Hi👋SpeedAlgo

Invariant-First Algorithmic Mastery

201Items
Theory Context•Two Pointers & Sliding Window
MediumLC 930

Binary Subarrays With Sum (LeetCode 930)

You will see how an exact count that no single window can track becomes the difference of two "at most" counts.

Target Frequency:GoogleAmazonMeta

You get an array nums in which every element is 0 or 1, and a whole number goal. A subarray is a run of one or more neighbouring elements of nums, taken without gaps. Count the subarrays whose elements add up to exactly goal, and return that number.

Subarrays are told apart by where they start and end: two runs at different positions both count, even if they hold the same values. When goal is 0, the subarrays made only of zeros are the ones that count.

Worked Examples

Example 1
Input:nums = [1,0,1,0,1], goal = 2
Output:4
1001120314111
Explanation: The runs with exactly two 1s are indices 0 to 2 (`1,0,1`), 0 to 3 (`1,0,1,0`), 1 to 4 (`0,1,0,1`) and 2 to 4 (`1,0,1`).
Example 2
Input:nums = [0,0,0,0,0], goal = 0
Output:15
0001020304
Explanation: Every run sums to 0, and five elements have 5 + 4 + 3 + 2 + 1 = 15 runs.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 3 * 104

  • nums[i] is either 0 or 1.

  • 0 <= goal <= nums.length

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

"Exactly goal" is not a window you can slide, because zeros join and leave without changing the sum; "at most limit" is, so count at_most(goal) - at_most(goal - 1), where at_most(-1) is 0.

Real-World Scenario & Production Applications

Counting time windows with an exact number of events: a monitoring system that asks how many stretches of a minute-by-minute log contain exactly two failed deploys counts "at most two" and "at most one" with two sliding windows and subtracts, instead of checking every stretch.

Step-by-Step Execution Trace Table

nums = [1,0,0,1,0], goal = 0 (the trap preset): the answer is at_most(0) - at_most(-1).

StepCallrightnums[right]window after shrinkingleftcount += right - left + 1
1at_most(0)011 > 0: drop nums[0], window 01+ 0 -> 0
2at_most(0)1001+ 1 -> 1
3at_most(0)2001+ 2 -> 3
4at_most(0)311 > 0: drop nums[1], nums[2], nums[3], window 04+ 0 -> 3
5at_most(0)4004+ 1 -> 4
6at_most(-1)limit < 0: return 0 at once0
7answer4 - 0 = 4
Scroll horizontally to see all columns, or expand to full screen

Step 3 adds 2: the zero runs [0] (index 2) and [0,0] (indices 1 to 2) both end at right = 2. Without the guard in step 6, at_most(-1) would look for a window with a negative sum, move left past right, and read past the end of nums.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1"Exactly `goal`" can't be slid, but "at most `limit`" can: count both `at_most(goal)` and `at_most(goal - 1)` and subtract.
2Keep this true: inside `at_most(limit)`, `nums[left..right]` is the longest window ending at `right` whose sum is at most `limit`.
3The shape: a helper `at_most(limit)` with one `for right` loop that grows the window, an inner loop that shrinks it from the left, and one addition to `count` per `right`; the answer combines two calls of the helper.
4The trap: `goal = 0` asks for `at_most(-1)`. Return 0 for a negative `limit`, or the shrink loop walks `left` off the end of `nums`.

Target: Binary Subarrays With Sum (LeetCode 930). No subarray of 0s and 1s has a negative sum, so `at_most(-1)` is 0; returning early also keeps the window from running off the end when `goal` is 0.

Boundary Model: Converging Boundaries [left, right] / Sliding Window [L, R]

Indices step monotonically inward or rightward. Each step permanently eliminates an entire row, column, or infeasible candidate window.

Loop Invariant Termination

while (left < right) for converging pointers; while (right < n) with inner window shrink.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Counting subarrays whose sum is exactly goal sounds like a sliding window, but it isn't one: in [0,0,1,0,0] with goal = 1, the 1 fits in nine different runs, and the zeros on both sides can join or leave without changing the sum. No single left edge describes them all. Counting subarrays whose sum is at most limit is a clean window: if nums[left..right] fits, every shorter window ending at right fits too, so for each right there is one smallest left, and right - left + 1 subarrays end there. The At-Most Trick counts two of those and subtracts: at_most(goal) - at_most(goal - 1) leaves exactly the sums equal to goal.

🧺 The Analogy: Shelves With a Weight Limit

A shelf holds at most 2 kilos. Knowing how many runs of books fit on a 2-kilo shelf, and how many fit on a 1-kilo shelf, tells you how many runs weigh more than 1 kilo but at most 2: subtract the two numbers. Counting runs that weigh exactly some amount directly is awkward, because weightless bookmarks can be added or removed at either end of a run.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
def at_most(limit):
if limit < 0:
return 0 # at_most(-1): nothing has a negative sum
left = window = count = 0
for right in range(len(nums)):
window += nums[right]
while window > limit:
window -= nums[left]
left += 1
count += right - left + 1 # every start from left to right fits
return count
 
return at_most(goal) - at_most(goal - 1)
 

Each subarray with sum at most goal has sum exactly goal or at most goal - 1, so the subtraction is exact. When goal is 0, the second call asks for a negative limit: no window can ever fit, so without the early return 0 the while loop would push left past right and off the end of nums.

💡 Summary

Exactly goal = at most goal minus at most goal - 1; each count is one sliding window that adds right - left + 1 per end, and at_most(-1) is 0. O(N)O(N)O(N) time, O(1)O(1)O(1) extra space.

  • A negative limit: goal = 0 asks for at_most(-1). if limit < 0: return 0, or the while window > limit loop walks left past right and off the end of nums.

  • Counting one subarray per end: add right - left + 1, not 1. Every start from left to right gives a subarray whose sum is at most limit.

  • Shrinking only once: use while window > limit, not if. After a 1 joins, nums[left] may be a 0, and one step leaves the sum over limit.

  • One window for "exactly": counting a window when its sum equals goal misses the runs that start at a zero the window already dropped; in [1,0,1,0,1] with goal = 2 it finds fewer than 4.

  • Keys left at zero, as in Subarrays with K Different Integers (LC 992): with different values as the amount, del a value whose count drops to 0, or len(copies) stays too high.

  • Not the only correct shape: a single window with two left pointers (one marking where it first reaches exactly k different values, one where it first exceeds k) also solves this in one pass; the at-most/at-most difference is preferred here because it reuses one window function instead of tracking two left edges.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer hears "count subarrays with exactly goal" and turns it into two "at most" windows.

Pattern Recognition Signals

The 10-second spot

"Count the subarrays whose elements add up to exactly goal" with "every element is 0 or 1": an exact count over subarrays, where adding an element never lowers the sum. "Exactly" can't be slid, but "at most" can, so the signal is the At-Most Trick: exactly(goal) = at_most(goal) - at_most(goal - 1). "When goal is 0" warns that at_most(-1) will be asked for.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Inside at_most(limit), after each right, nums[left..right] is the longest window ending at right whose sum is at most limit, so count += right - left + 1 adds every such subarray once; the answer is at_most(goal) - at_most(goal - 1).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • goal = 0 makes at_most(goal - 1) into at_most(-1): if limit < 0: return 0, or while window > limit walks left past right and off the end of nums.

  • count += right - left + 1, not count += 1: in [0,0,0,0,0] with goal = 0 each new zero ends several all-zero runs at once.

  • while window > limit, not if: after a 1 joins, nums[left] may be a 0, and one step leaves the sum over limit.

  • One window for "exactly" misses subarrays: in [1,0,1,0,1] with goal = 2, the run 0,1,0,1 starts at a 0 that such a window has already dropped.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use the At-Most Trick. Counting subarrays whose sum is exactly goal with one window doesn't work, because zeros can join or leave without changing the sum, so there's no single left edge to track. Counting subarrays whose sum is at most some limit does work: I grow the window to the right, shrink it from the left while the sum is over the limit, and add right minus left plus one for every right end, since every start inside the window fits. Then exactly goal is at most goal minus at most goal minus one, because each subarray lands in exactly one of those two groups. The trap is goal equal to zero: that asks for at most minus one, which has to be zero, so I return early for a negative limit instead of letting the window run off the end. Two passes, O(N) time and O(1) space.

So: exactly = at most goal minus at most goal - 1; each count adds right - left + 1 per end; at_most(-1) is 0.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

at_most(limit) runs for right in range(len(nums)): N steps, each with one addition and one count +=. The inner while window > limit moves left one place per step, and left only moves forward and never passes N, so across the whole pass the while body runs at most N times in all. One pass is O(N). num_subarrays_with_sum makes two passes, at_most(goal) and at_most(goal - 1) (the second returns at once when goal is 0): O(2N) = O(N).

SPACE COMPLEXITY

O(1)

Each pass keeps limit, left, window, count and right: O(1) extra space. The two calls run one after the other, so the stack never holds more than one at_most frame. The answer is one integer.

Formal Recurrence Relation

T(N) = 2 passes x (N moves of right + at most N moves of left) = O(N)

at_most(limit) runs for right in range(len(nums)): N steps, each with one addition and one count +=. The inner while window > limit moves left one place per step, and left only moves forward and never passes N, so across the whole pass the while body runs at most N times in all. One pass is O(N). num_subarrays_with_sum makes two passes, at_most(goal) and at_most(goal - 1) (the second returns at once when goal is 0): O(2N) = O(N).

Derivation Progression

Grow

N

for right in range(len(nums)) adds each element to window once per pass.

Shrink

at most N

Each run of the while body moves left forward by one; left never moves back and never passes N, so all shrinks in a pass add up to at most N.

Count

N

count += right - left + 1 is one addition per right, however many subarrays it counts.

Two passes

O(N)

at_most(goal) and at_most(goal - 1) each cost O(N); their difference is one subtraction.

Variable Definitions

NNN

Number of elements, len(nums) (at most 3 * 10^4)

Memory Architecture & Bounds

🟣 Call Stack

O(1): one at_most frame at a time

🔵 Auxiliary Heap

O(1): limit, left, window, count, right

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): goal = 0, so the second pass returns at once, but the first still reads every element

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N): two full passes, with left crossing the whole array in each

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: **"add up to exactly goal"**, **"every element is 0or1"**, "Count the subarrays". An exact count over subarrays whose amount only grows as elements join: At-Most Trick, at_most(goal) - at_most(goal - 1).

CONSTRAINTS & BOUNDS

Up to 3×1043 \times 10^43×104 elements. Checking every subarray is about 4.5×1084.5 \times 10^84.5×108 additions; two sliding-window passes are about 1.2×1051.2 \times 10^51.2×105 pointer moves. The answer can reach N(N+1)/2≈4.5×108N(N + 1) / 2 \approx 4.5 \times 10^8N(N+1)/2≈4.5×108, which still fits a 32-bit integer, but at 10510^5105 elements it would not.

FAANG PRODUCTION TRAPS & EDGE CASES

goal = 0 asks for at_most(-1), which must be 0 rather than a loop that reads past the end. On a stream, the two counts can run side by side as two windows over the same input, so the log is read once; the same subtraction answers "exactly K events in a window" as long as events only add, never cancel. Counts over long streams outgrow 32 bits quickly: keep them in 64-bit integers.

Core Algorithmic State Invariants

1. At Most Is a Window, Exactly Is Not

Zeros join and leave without changing the sum, so no single window tracks "exactly `goal`". "At most `limit`" only shrinks from the left, so one pass counts it.

2. at_most(-1) Is Zero

For `goal = 0` the second count is `at_most(-1)`. `if limit < 0: return 0`, or `while window > limit` walks `left` past `right` and off the end of `nums`.

3. Two Linear Passes

Each pass moves `right` and `left` forward at most `N` times and adds `right - left + 1` per end: O(N) time, O(1) extra space, for both counts together.

Theory Context•Two Pointers & Sliding Window
MediumLC 930

Binary Subarrays With Sum (LeetCode 930)

You will see how an exact count that no single window can track becomes the difference of two "at most" counts.

Target Frequency:GoogleAmazonMeta

You get an array nums in which every element is 0 or 1, and a whole number goal. A subarray is a run of one or more neighbouring elements of nums, taken without gaps. Count the subarrays whose elements add up to exactly goal, and return that number.

Subarrays are told apart by where they start and end: two runs at different positions both count, even if they hold the same values. When goal is 0, the subarrays made only of zeros are the ones that count.

Worked Examples

Example 1
Input:nums = [1,0,1,0,1], goal = 2
Output:4
1001120314111
Explanation: The runs with exactly two 1s are indices 0 to 2 (`1,0,1`), 0 to 3 (`1,0,1,0`), 1 to 4 (`0,1,0,1`) and 2 to 4 (`1,0,1`).
Example 2
Input:nums = [0,0,0,0,0], goal = 0
Output:15
0001020304
Explanation: Every run sums to 0, and five elements have 5 + 4 + 3 + 2 + 1 = 15 runs.

⚖️Formal Constraints & Bounds

  • 1 <= nums.length <= 3 * 104

  • nums[i] is either 0 or 1.

  • 0 <= goal <= nums.length

Deep-Dive & Conceptual Insights

Why It Works & Core Invariant

"Exactly goal" is not a window you can slide, because zeros join and leave without changing the sum; "at most limit" is, so count at_most(goal) - at_most(goal - 1), where at_most(-1) is 0.

Real-World Scenario & Production Applications

Counting time windows with an exact number of events: a monitoring system that asks how many stretches of a minute-by-minute log contain exactly two failed deploys counts "at most two" and "at most one" with two sliding windows and subtracts, instead of checking every stretch.

Step-by-Step Execution Trace Table

nums = [1,0,0,1,0], goal = 0 (the trap preset): the answer is at_most(0) - at_most(-1).

StepCallrightnums[right]window after shrinkingleftcount += right - left + 1
1at_most(0)011 > 0: drop nums[0], window 01+ 0 -> 0
2at_most(0)1001+ 1 -> 1
3at_most(0)2001+ 2 -> 3
4at_most(0)311 > 0: drop nums[1], nums[2], nums[3], window 04+ 0 -> 3
5at_most(0)4004+ 1 -> 4
6at_most(-1)limit < 0: return 0 at once0
7answer4 - 0 = 4
Scroll horizontally to see all columns, or expand to full screen

Step 3 adds 2: the zero runs [0] (index 2) and [0,0] (indices 1 to 2) both end at right = 2. Without the guard in step 6, at_most(-1) would look for a window with a negative sum, move left past right, and read past the end of nums.

Core Invariant Specification & Code Shape
Archetype Code Shape
Python
1"Exactly `goal`" can't be slid, but "at most `limit`" can: count both `at_most(goal)` and `at_most(goal - 1)` and subtract.
2Keep this true: inside `at_most(limit)`, `nums[left..right]` is the longest window ending at `right` whose sum is at most `limit`.
3The shape: a helper `at_most(limit)` with one `for right` loop that grows the window, an inner loop that shrinks it from the left, and one addition to `count` per `right`; the answer combines two calls of the helper.
4The trap: `goal = 0` asks for `at_most(-1)`. Return 0 for a negative `limit`, or the shrink loop walks `left` off the end of `nums`.

Target: Binary Subarrays With Sum (LeetCode 930). No subarray of 0s and 1s has a negative sum, so `at_most(-1)` is 0; returning early also keeps the window from running off the end when `goal` is 0.

Boundary Model: Converging Boundaries [left, right] / Sliding Window [L, R]

Indices step monotonically inward or rightward. Each step permanently eliminates an entire row, column, or infeasible candidate window.

Loop Invariant Termination

while (left < right) for converging pointers; while (right < n) with inner window shrink.

Conceptual Narrative

🧭 Conceptual Foundation & Pattern Intuition

Counting subarrays whose sum is exactly goal sounds like a sliding window, but it isn't one: in [0,0,1,0,0] with goal = 1, the 1 fits in nine different runs, and the zeros on both sides can join or leave without changing the sum. No single left edge describes them all. Counting subarrays whose sum is at most limit is a clean window: if nums[left..right] fits, every shorter window ending at right fits too, so for each right there is one smallest left, and right - left + 1 subarrays end there. The At-Most Trick counts two of those and subtracts: at_most(goal) - at_most(goal - 1) leaves exactly the sums equal to goal.

🧺 The Analogy: Shelves With a Weight Limit

A shelf holds at most 2 kilos. Knowing how many runs of books fit on a 2-kilo shelf, and how many fit on a 1-kilo shelf, tells you how many runs weigh more than 1 kilo but at most 2: subtract the two numbers. Counting runs that weigh exactly some amount directly is awkward, because weightless bookmarks can be added or removed at either end of a run.

🪄 The Mathematical Harmony / Magic Trick
Code / Blueprint
def at_most(limit):
if limit < 0:
return 0 # at_most(-1): nothing has a negative sum
left = window = count = 0
for right in range(len(nums)):
window += nums[right]
while window > limit:
window -= nums[left]
left += 1
count += right - left + 1 # every start from left to right fits
return count
 
return at_most(goal) - at_most(goal - 1)
 

Each subarray with sum at most goal has sum exactly goal or at most goal - 1, so the subtraction is exact. When goal is 0, the second call asks for a negative limit: no window can ever fit, so without the early return 0 the while loop would push left past right and off the end of nums.

💡 Summary

Exactly goal = at most goal minus at most goal - 1; each count is one sliding window that adds right - left + 1 per end, and at_most(-1) is 0. O(N)O(N)O(N) time, O(1)O(1)O(1) extra space.

  • A negative limit: goal = 0 asks for at_most(-1). if limit < 0: return 0, or the while window > limit loop walks left past right and off the end of nums.

  • Counting one subarray per end: add right - left + 1, not 1. Every start from left to right gives a subarray whose sum is at most limit.

  • Shrinking only once: use while window > limit, not if. After a 1 joins, nums[left] may be a 0, and one step leaves the sum over limit.

  • One window for "exactly": counting a window when its sum equals goal misses the runs that start at a zero the window already dropped; in [1,0,1,0,1] with goal = 2 it finds fewer than 4.

  • Keys left at zero, as in Subarrays with K Different Integers (LC 992): with different values as the amount, del a value whose count drops to 0, or len(copies) stays too high.

  • Not the only correct shape: a single window with two left pointers (one marking where it first reaches exactly k different values, one where it first exceeds k) also solves this in one pass; the at-most/at-most difference is preferred here because it reuses one window function instead of tracking two left edges.

Senior SWE Reasoning Architecture

4-Phase Thought Process Model

You will see how a senior engineer hears "count subarrays with exactly goal" and turns it into two "at most" windows.

Pattern Recognition Signals

The 10-second spot

"Count the subarrays whose elements add up to exactly goal" with "every element is 0 or 1": an exact count over subarrays, where adding an element never lowers the sum. "Exactly" can't be slid, but "at most" can, so the signal is the At-Most Trick: exactly(goal) = at_most(goal) - at_most(goal - 1). "When goal is 0" warns that at_most(-1) will be asked for.

Formulating the Predicate & Invariants

Turning intuition into a boolean rule

Inside at_most(limit), after each right, nums[left..right] is the longest window ending at right whose sum is at most limit, so count += right - left + 1 adds every such subarray once; the answer is at_most(goal) - at_most(goal - 1).

Silent Failure Traps & Edge Cases

Where confident candidates still lose points

  • goal = 0 makes at_most(goal - 1) into at_most(-1): if limit < 0: return 0, or while window > limit walks left past right and off the end of nums.

  • count += right - left + 1, not count += 1: in [0,0,0,0,0] with goal = 0 each new zero ends several all-zero runs at once.

  • while window > limit, not if: after a 1 joins, nums[left] may be a 0, and one step leaves the sum over limit.

  • One window for "exactly" misses subarrays: in [1,0,1,0,1] with goal = 2, the run 0,1,0,1 starts at a 0 that such a window has already dropped.

The 60-Second Interview Pitch

Say this out loud before you type a single line

I'd use the At-Most Trick. Counting subarrays whose sum is exactly goal with one window doesn't work, because zeros can join or leave without changing the sum, so there's no single left edge to track. Counting subarrays whose sum is at most some limit does work: I grow the window to the right, shrink it from the left while the sum is over the limit, and add right minus left plus one for every right end, since every start inside the window fits. Then exactly goal is at most goal minus at most goal minus one, because each subarray lands in exactly one of those two groups. The trap is goal equal to zero: that asks for at most minus one, which has to be zero, so I return early for a negative limit instead of letting the window run off the end. Two passes, O(N) time and O(1) space.

So: exactly = at most goal minus at most goal - 1; each count adds right - left + 1 per end; at_most(-1) is 0.

Big-O Invariant Derivation

Complexity & Mathematical Proof

TIME COMPLEXITY

O(N)

at_most(limit) runs for right in range(len(nums)): N steps, each with one addition and one count +=. The inner while window > limit moves left one place per step, and left only moves forward and never passes N, so across the whole pass the while body runs at most N times in all. One pass is O(N). num_subarrays_with_sum makes two passes, at_most(goal) and at_most(goal - 1) (the second returns at once when goal is 0): O(2N) = O(N).

SPACE COMPLEXITY

O(1)

Each pass keeps limit, left, window, count and right: O(1) extra space. The two calls run one after the other, so the stack never holds more than one at_most frame. The answer is one integer.

Formal Recurrence Relation

T(N) = 2 passes x (N moves of right + at most N moves of left) = O(N)

at_most(limit) runs for right in range(len(nums)): N steps, each with one addition and one count +=. The inner while window > limit moves left one place per step, and left only moves forward and never passes N, so across the whole pass the while body runs at most N times in all. One pass is O(N). num_subarrays_with_sum makes two passes, at_most(goal) and at_most(goal - 1) (the second returns at once when goal is 0): O(2N) = O(N).

Derivation Progression

Grow

N

for right in range(len(nums)) adds each element to window once per pass.

Shrink

at most N

Each run of the while body moves left forward by one; left never moves back and never passes N, so all shrinks in a pass add up to at most N.

Count

N

count += right - left + 1 is one addition per right, however many subarrays it counts.

Two passes

O(N)

at_most(goal) and at_most(goal - 1) each cost O(N); their difference is one subtraction.

Variable Definitions

NNN

Number of elements, len(nums) (at most 3 * 10^4)

Memory Architecture & Bounds

🟣 Call Stack

O(1): one at_most frame at a time

🔵 Auxiliary Heap

O(1): limit, left, window, count, right

🟢 Output Space

O(1): one integer

Boundary Best / Worst Cases

Best Case

O(N)O(N)O(N): goal = 0, so the second pass returns at once, but the first still reads every element

Average Case

O(N)O(N)O(N)

Worst Case

O(N)O(N)O(N): two full passes, with left crossing the whole array in each

Pointer Invariant Transition Progression

Pointer Invariant Transition Progression
Synthesizing vector architecture diagram...
Staff+ Engineering Perspective

Senior SWE Deconstruction & Hardware Caveats

ARCHITECTURAL SIGNALS & INTERVIEW TRIGGERS

Triggers: **"add up to exactly goal"**, **"every element is 0or1"**, "Count the subarrays". An exact count over subarrays whose amount only grows as elements join: At-Most Trick, at_most(goal) - at_most(goal - 1).

CONSTRAINTS & BOUNDS

Up to 3×1043 \times 10^43×104 elements. Checking every subarray is about 4.5×1084.5 \times 10^84.5×108 additions; two sliding-window passes are about 1.2×1051.2 \times 10^51.2×105 pointer moves. The answer can reach N(N+1)/2≈4.5×108N(N + 1) / 2 \approx 4.5 \times 10^8N(N+1)/2≈4.5×108, which still fits a 32-bit integer, but at 10510^5105 elements it would not.

FAANG PRODUCTION TRAPS & EDGE CASES

goal = 0 asks for at_most(-1), which must be 0 rather than a loop that reads past the end. On a stream, the two counts can run side by side as two windows over the same input, so the log is read once; the same subtraction answers "exactly K events in a window" as long as events only add, never cancel. Counts over long streams outgrow 32 bits quickly: keep them in 64-bit integers.

Core Algorithmic State Invariants

1. At Most Is a Window, Exactly Is Not

Zeros join and leave without changing the sum, so no single window tracks "exactly `goal`". "At most `limit`" only shrinks from the left, so one pass counts it.

2. at_most(-1) Is Zero

For `goal = 0` the second count is `at_most(-1)`. `if limit < 0: return 0`, or `while window > limit` walks `left` past `right` and off the end of `nums`.

3. Two Linear Passes

Each pass moves `right` and `left` forward at most `N` times and adds `right - left + 1` per end: O(N) time, O(1) extra space, for both counts together.

Rosetta Dual-Monaco Comparison
Python 3
CANONICAL INVARIANT TEMPLATE
Loading...
CONCRETE: BINARY SUBARRAYS WITH SUM (LEETCODE 930)
T = O(N)S = O(1)
Loading...
Pattern Implementation Mapping TableCanonical Invariant ⟷ Concrete Code ⟷ Engineering Rationale
Canonical InvariantConcrete CodeEngineering Rationale
"At most" for a negative limit is empty (the trap)if limit < 0: return 0No subarray of 0s and 1s has a negative sum, so `at_most(-1)` is 0; returning early also keeps the window from running off the end when `goal` is 0.
Grow the window by one elementwindow += nums[right]`right` moves once per step, and the window's sum takes in the new element.
Shrink from the left until the window fitswhile window > limit:The values are never negative, so dropping elements from the left can only lower the sum; a `while` keeps dropping until it is at most `limit`.
Drop the leftmost elementwindow -= nums[left] left += 1`left` only moves forward, so across a pass it moves at most N times.
Count every start that fitscount += right - left + 1Every window from `left..right` down to `right..right` has a sum at most `limit`, so one addition counts them all.
Exactly = at most minus at most one lessreturn at_most(goal) - at_most(goal - 1)A subarray with sum at most `goal` has sum `goal` or at most `goal - 1`, never both, so the difference counts the sums equal to `goal`.
© 2026 Hi👋WebEnterprise. All rights reserved.
Sitemap•llms.txt•