{"id":"binary-subarrays-with-sum","title":"Binary Subarrays With Sum","difficulty":"medium","patterns":["prefix-sum","hash-map"],"primaryConcept":"array-prefix-sum-hash","concepts":["array-prefix-sum-hash"],"problemForm":"core","companies":["Meta","Google","Amazon","Microsoft"],"category":"arrays-strings","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"array-scalar","primaryParam":"nums","secondaryParam":"goal","sizeMetric":"length","constraints":["binary"],"secondaryParams":{"goal":{"strategy":"proportion","proportion":0.5}},"sizes":[8,16,32,64]},"description":"Given a binary array `nums` and an integer `goal`, return the number of non-empty contiguous subarrays whose sum is exactly `goal`.\n\nBecause `nums` contains only `0` and `1`, repeated prefix sums are common. Count every valid starting point, not just whether one exists.","examples":[{"input":"nums = [1,0,1,0,1], goal = 2","output":"4","explanation":"The valid subarrays are [1,0,1], [1,0,1,0], [1,0,1], and [1,0,1] at different positions."},{"input":"nums = [0,0,0,0,0], goal = 0","output":"15","explanation":"Every non-empty subarray sums to 0."},{"input":"nums = [1,1,1,1], goal = 3","output":"2","explanation":"Only the two length-3 windows sum to 3."}],"constraints":[{"id":"1-len-nums-3-10-4","text":"1 <= len(nums) <= 3 * 10^4","check":{"kind":"sizeRange","target":"nums","measure":"arrayLength","min":1,"max":30000}},{"id":"nums-i-is-0-or-1","text":"nums[i] is 0 or 1","check":{"kind":"domain","target":"nums","selector":"arrayItems","allowed":[0,1]}},{"id":"0-goal-len-nums","text":"0 <= goal <= len(nums)","check":{"kind":"valueRange","target":"goal","selector":"value","min":0,"max":{"sizeOfInput":"nums","measure":"arrayLength"}}}],"starterCode":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        # Your code here\n        pass","functionName":"numSubarraysWithSum","testCases":[{"id":"1","input":{"nums":[1,0,1,0,1],"goal":2},"expected":4,"description":"Standard overlapping binary subarrays."},{"id":"2","input":{"nums":[0,0,0,0,0],"goal":0},"expected":15,"description":"All-zero array counts every subarray."},{"id":"3","input":{"nums":[0,0,0,0,0],"goal":1},"expected":0,"description":"No subarray can reach a positive goal."},{"id":"4","input":{"nums":[1,1,1,1],"goal":3},"expected":2,"description":"Two length-three windows."},{"id":"5","input":{"nums":[1,0,1,0,1],"goal":0},"expected":2,"description":"Only the individual zero runs sum to 0."},{"id":"h1","input":{"nums":[1],"goal":1},"expected":1,"description":"Single one."},{"id":"h2","input":{"nums":[0],"goal":0},"expected":1,"description":"Single zero."},{"id":"h3","input":{"nums":[1,0,0,1,0,1,0,0],"goal":2},"expected":11,"description":"Multiple repeated prefix sums around two ones."},{"id":"h4","input":{"nums":[1,0,1,0,1,0],"goal":2},"expected":6,"description":"Repeated zero padding creates several overlapping goal-2 subarrays."},{"id":"h5","input":{"nums":[0,1,0,1,0],"goal":1},"expected":8,"description":"Each isolated one can be extended by surrounding zeros in multiple ways."},{"id":"h6","input":{"nums":[0,0,0,0],"goal":0},"expected":10,"description":"Every non-empty subarray of all zeros has sum zero."},{"id":"h7","input":{"nums":[1,0,0,1,0,0,1],"goal":2},"expected":6,"description":"A run of ones has only two length-three windows with sum three."}],"hints":[{"level":1,"content":"For each ending index, ask how many earlier prefix sums would make the subarray sum equal `goal`.","revealPattern":false},{"level":2,"content":"Track how many times each prefix sum has appeared. If the current sum is `S`, you need earlier prefix sum `S - goal`.","revealPattern":true},{"level":3,"content":"Seed the prefix-count map with `{0: 1}` so subarrays starting at index 0 are counted.","revealPattern":true}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"brute-force","name":"Check every subarray","summary":"Try every start and end index and sum the range.","decisionReason":"This recomputes each range from endpoints and keeps no reusable history of earlier prefix sums, so every new end index repeats work.","complexity":{"time":"O(n^2)","space":"O(1)"},"tradeoffs":["It uses little extra space, but it does not preserve the prior-prefix invariant needed to count all starts in one lookup."],"isOptimal":false},{"id":"prefix-counts","name":"Prefix sums with counts","summary":"Scan once, look up current prefix minus goal, and store prefix-sum frequencies.","decisionReason":"The map preserves how many earlier prefixes have each sum; `currentPrefix-goal` directly finds all valid starts for the current end index.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["It spends O(n) space on prefix frequencies so each index can update the answer from prior state in O(1) average time."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-variables","title":"Seed prefix state","description":"Initialize the answer count, the running prefix sum, and the map with the zero-prefix seed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"initializes_seeded_lookup_scan_state","scope":"init-variables","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Forgetting the `{0: 1}` seed","Starting count or prefix sum at a nonzero value"],"hint":"The zero-prefix seed represents a start before index 0, so subarrays beginning at the first element can be counted by the same lookup rule.","semanticSpec":{"intent":"Seed the prefix-count scan state.","doneWhen":"The answer and running prefix sum start at zero, and the prefix map records one zero prefix.","shouldFailWhen":"This step should fail if the zero-prefix seed is missing.","roles":["answer count","running prefix sum","prefix-count map"],"mustProve":["The map is seeded with prefix sum 0 before the loop."],"mustNotAccept":["An unseeded map."],"proofSnippets":[{"id":"py-binary-subarrays-seed-prefix-state","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}"}]}},{"id":"scan-nums","title":"Scan every number","description":"Visit each element once so every subarray ending position is considered.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"scans_input_sequence","scope":"loop-through-nums","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Skipping zeros","Stopping after the first match"],"hint":"Every index can be the end of many valid subarrays.","semanticSpec":{"intent":"Scan the input sequence once.","doneWhen":"The main loop visits each number in `nums`.","shouldFailWhen":"This step should fail if the scan does not iterate over the input sequence.","roles":["input sequence","current number"],"mustProve":["The traversal reads each input element."],"mustNotAccept":["A fixed-count loop unrelated to `nums`.","A replay of only selected sample indices from the guided trace."],"proofSnippets":[{"id":"py-binary-subarrays-scan-nums","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            pass"}]}},{"id":"update-prefix-sum","title":"Update the running prefix sum","description":"Add the current number to the running prefix sum.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"additively_updates_accumulator","scope":"update-prefix-sum","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Replacing the prefix sum with the current number","Updating the map before the current lookup"],"hint":"The prefix sum is the total of all values seen so far.","semanticSpec":{"intent":"Maintain the cumulative prefix sum.","doneWhen":"The current number is added to the running prefix state.","shouldFailWhen":"This step should fail if the running sum is reset.","roles":["running prefix sum","current number"],"mustProve":["The current element is added into the accumulator."],"mustNotAccept":["Assigning the current number directly to the prefix sum."],"proofSnippets":[{"id":"py-binary-subarrays-update-prefix-sum","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            prefix_sum += num"}]}},{"id":"check-needed-prefix","title":"Look up the needed earlier prefix","description":"Compute the needed previous prefix and read its already-seen frequency before recording the current prefix.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"checks_difference_derived_lookup","scope":"check-previous-sum","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Looking up `prefix_sum` instead of the needed previous prefix","Adding `goal` instead of subtracting it","Recording the current prefix before the lookup"],"hint":"If current prefix is S, only prefixes seen before this index can serve as starts for subarrays ending here.","semanticSpec":{"intent":"Use a difference-derived lookup against prior prefix counts.","doneWhen":"For each current prefix sum S, the solution derives `S - goal` and reads that key from the existing prefix-count map before the current prefix is inserted for future indices.","shouldFailWhen":"This step should fail if the raw prefix sum is checked instead, if the current prefix is inserted before the lookup, or if the lookup is hard-coded to values from the trace example.","roles":["current prefix","goal","needed prefix","prior prefix-count map"],"mustProve":["The lookup key is derived from the current prefix sum and goal, not from a fixed sample value.","The needed-prefix lookup reads the map before the current prefix is counted as a previous prefix."],"mustNotAccept":["Checking the raw prefix sum.","Updating the map for the current prefix before checking the needed prefix.","Special-casing only the trace's needed prefix values."],"proofSnippets":[{"id":"py-binary-subarrays-check-needed-prefix","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            prefix_sum += num\n            needed = prefix_sum - goal\n            if needed in prefix_counts:\n                matching_starts = prefix_counts[needed]"}]}},{"id":"update-count","title":"Add all matching starts","description":"Add the stored frequency for the needed prefix to the answer.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"increments_accumulator_by_lookup_result","scope":"update-count","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Adding only 1 for a match instead of the stored frequency","Overwriting the answer count"],"hint":"Repeated earlier prefix sums represent multiple starting positions.","semanticSpec":{"intent":"Count all subarrays ending at the current index.","doneWhen":"The answer increases by the stored frequency for the needed prefix, so a needed prefix seen two or more times contributes that many starting positions.","shouldFailWhen":"This step should fail if multiplicity is ignored, if every lookup hit adds only 1, or if the count update only works for the trace's first match.","roles":["answer count","matching prefix count"],"mustProve":["The result is incremented by the lookup value.","A stored prefix frequency greater than 1 can add more than one valid subarray ending at the same index."],"mustNotAccept":["Treating the lookup as a boolean hit only.","Overwriting the accumulated answer with the lookup value."],"proofSnippets":[{"id":"py-binary-subarrays-add-matching-starts","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            prefix_sum += num\n            needed = prefix_sum - goal\n            if needed in prefix_counts:\n                count += prefix_counts[needed]"}]}},{"id":"update-map","title":"Record the current prefix","description":"Increment the frequency of the current prefix sum after using it for the current index.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"keyed-state","fact":"updates_keyed_counter_after_lookup_consumption","scope":"update-map","readMode":"keyed-state-value-query-v1"}]},"commonMistakes":["Updating the map before checking the needed prefix","Storing a set of seen prefixes instead of counts, which forgets how many earlier positions share a total"],"hint":"The current prefix becomes an earlier prefix for future positions.","semanticSpec":{"intent":"Preserve prefix-sum multiplicity for future lookups.","doneWhen":"After the needed-prefix lookup has been consumed for the current index, the current prefix-sum key is incremented in the map for later indices.","shouldFailWhen":"This step should fail if the frequency map is updated too early, overwritten, or treated as a set of seen prefixes.","roles":["prefix-count map","current prefix"],"mustProve":["The current prefix frequency is incremented after the lookup.","Repeated current prefix sums accumulate multiplicity instead of replacing the old count."],"mustNotAccept":["Replacing an existing count with a constant.","Using boolean presence instead of numeric frequency."],"proofSnippets":[{"id":"py-binary-subarrays-record-current-prefix","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            prefix_sum += num\n            needed = prefix_sum - goal\n            if needed in prefix_counts:\n                count += prefix_counts[needed]\n            prefix_counts[prefix_sum] = prefix_counts.get(prefix_sum, 0) + 1"}]}},{"id":"return-result","title":"Return the final count","description":"Return the accumulated number of valid subarrays after the scan.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"array-scan","fact":"returns_terminal_accumulator","scope":"return-result","readMode":"array-scan-value-query-v1"}]},"commonMistakes":["Returning the prefix sum","Returning the map"],"hint":"Return the answer accumulator.","semanticSpec":{"intent":"Return the terminal accumulated count.","doneWhen":"The function returns the result accumulator after the loop.","shouldFailWhen":"This step should fail if a prefix sum or map is returned.","roles":["final count","return value"],"mustProve":["The final return is the accumulated count."],"mustNotAccept":["Returning the prefix-count map."],"proofSnippets":[{"id":"py-binary-subarrays-return-count","language":"python","code":"class Solution:\n    def numSubarraysWithSum(self, nums: list[int], goal: int) -> int:\n        count = 0\n        prefix_sum = 0\n        prefix_counts = {0: 1}\n        for num in nums:\n            prefix_sum += num\n            needed = prefix_sum - goal\n            if needed in prefix_counts:\n                count += prefix_counts[needed]\n            prefix_counts[prefix_sum] = prefix_counts.get(prefix_sum, 0) + 1\n        return count"}]}}],"slides":[{"id":"the-task","chapter":"The problem","kind":"info","eyebrow":"Read the problem","title":"Count the windows the ones make","workspacePanel":"problem","body":["nums holds only 0s and 1s. Given a goal, count how many contiguous, non-empty stretches add up to exactly goal.","The obvious way is to sum every stretch. Watch it work, and watch what it spends."]},{"id":"brute-force","chapter":"The problem","kind":"code-trace","eyebrow":"The obvious way","title":"Sum every stretch","summary":"Correct, but every new start rebuilds a tail sum from scratch.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"count = 0\nfor i in range(len(nums)):\n    total = 0\n    for j in range(i, len(nums)):\n        total += nums[j]\n        if total == goal:\n            count += 1\nreturn count","steps":[{"id":"first-sweep","title":"The sweep from index 0","codeLine":5,"summary":"total grows 1, 1, 2, 2, 3 as j extends. It equals goal at j = 2 and j = 3: two hits from this one start.","state":{"nums":[1,0,1,0,1],"left":0,"right":4,"total":3,"count":2,"goal":2,"labels":{"left":"i","right":"j"}}},{"id":"second-sweep","title":"Start over at index 1","codeLine":2,"summary":"New start, total rebuilt from zero: 0, 1, 1, 2. The inner loop walks the tail again from scratch.","state":{"nums":[1,0,1,0,1],"left":1,"right":4,"total":2,"count":3,"goal":2,"labels":{"left":"i","right":"j"}}},{"id":"all-sweeps","title":"Every start re-sums its tail","codeLine":5,"summary":"Each start zeroes total and re-adds the elements to its right, so the later starts keep re-summing the same trailing values.","state":{"nums":[1,0,1,0,1],"left":2,"right":4,"total":2,"count":4,"goal":2,"labels":{"left":"i","right":"j"}}},{"id":"tally-the-work","title":"Add up the additions","codeLine":5,"summary":"Line up the cost per start: start 0 runs 5 additions, start 1 runs 4, then 3, 2, 1. That triangle sums to 15 additions for a length-5 array.","state":{"rows":[{"label":"start i","values":[0,1,2,3,4]},{"label":"additions","values":[5,4,3,2,1],"changed":[0,1,2,3,4]}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let count = 0;\nfor (let i = 0; i < nums.length; i++) {\n    let total = 0;\n    for (let j = i; j < nums.length; j++) {\n        total += nums[j];\n        if (total === goal) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let count = 0;\nfor (let i = 0; i < nums.length; i++) {\n    let total = 0;\n    for (let j = i; j < nums.length; j++) {\n        total += nums[j];\n        if (total === goal) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.size(); i++) {\n    int total = 0;\n    for (int j = i; j < nums.size(); j++) {\n        total += nums.get(j);\n        if (total == goal) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.Count; i++) {\n    int total = 0;\n    for (int j = i; j < nums.Count; j++) {\n        total += nums[j];\n        if (total == goal) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11},"statementBundles":{"7":{"startLine":7,"endLine":10}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int count = 0;\nfor (int i = 0; i < nums.size(); i++) {\n    int total = 0;\n    for (int j = i; j < nums.size(); j++) {\n        total += nums[j];\n        if (total == goal) {\n            count++;\n        }\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":11},"statementBundles":{"7":{"startLine":7,"endLine":10}}}}},"body":["Pick each start, extend rightward, keep a running total, count the hits."]},{"id":"brute-cost-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Count the work","title":"How many additions do the nested loops run?","workspacePanel":"trace","summary":"Each start re-sums its whole tail: start 0 adds 5 values, start 1 adds 4, then 3, 2, 1.","options":[{"id":"quadratic","label":"About n^2 / 2: the work grows with the square of the length","rationale":"Start 0 sums n values, start 1 sums n-1, and so on down to 1. That is n + (n-1) + ... + 1, which is n^2 / 2. Double the array and the additions roughly quadruple.","isCorrect":true},{"id":"linear","label":"About n: one addition per element","rationale":"One pass would be n additions, but each start restarts its own sum and walks the tail again, so the same trailing values get added once per start.","isCorrect":false},{"id":"n-log-n","label":"About n log n: the range halves each step","rationale":"Nothing halves here. Both loops are linear in n, so they compound to n^2, not n log n.","isCorrect":false}],"answer":"The additions pile up to n^2 / 2. The waste is concrete: every later start re-sums trailing values an earlier start already added."},{"id":"see-the-prefixes","chapter":"The problem","kind":"info","eyebrow":"Put the totals on the board","title":"The totals were already there","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"see-the-prefixes-state","state":{"rows":[{"label":"nums","values":[1,0,1,0,1]},{"label":"prefix","values":[1,1,2,2,3]}],"goal":2}}]},"body":["Lay the from-the-start totals next to the array: prefix[j] is the sum of nums[0..j]. The brute force computed these over and over, one start at a time, and threw them away.","Keep them on the board and look at how a window relates to two of them."]},{"id":"prefix-identity-probe","chapter":"The problem","kind":"case-probe","eyebrow":"Name the waste","title":"How do the running totals relate?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"prefix-identity-state","state":{"rows":[{"label":"nums","values":[1,0,1,0,1]},{"label":"prefix","values":[1,1,2,2,3],"changed":[0,2]}],"i":2,"goal":2}}]},"summary":"Sweep i = 1 rebuilt sum[1..2] from scratch; the from-the-start totals prefix[0] = 1 and prefix[2] = 2 were already on the board.","options":[{"id":"prefix-difference","label":"Every stretch is a difference of two from-the-start totals: sum[1..2] = total[0..2] - total[0..0]","rationale":"Chop the front off a running total and a window sum falls out. From-the-start totals are the only sums anyone ever needed.","isCorrect":true},{"id":"no-relation","label":"They are unrelated: different stretches, different sums","rationale":"The values differ, but every sweep-1 total is a sweep-0 total minus nums[0]. That fixed offset is the relationship the rewrite exploits.","isCorrect":false},{"id":"off-by-goal","label":"They differ by goal whenever there is a hit","rationale":"Closer than it looks, but the relation holds always, not only at hits: any window is a difference of two from-the-start totals. The hits are where that difference equals goal.","isCorrect":false}],"answer":"Window sums are prefix differences: sum[i..j] = prefix[j] - prefix[i-1]. The brute force recomputed prefixes endlessly and never noticed it had them."},{"id":"idea-bridge","chapter":"The idea","kind":"info","eyebrow":"Carry the identity forward","title":"Two from-the-start totals per window","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"idea-bridge-state","state":{"rows":[{"label":"nums","values":[1,0,1,0,1]},{"label":"prefix","values":[1,1,2,2,3],"changed":[0,2,4]}],"i":4,"goal":2}}]},"body":["Every window sum reads as two from-the-start totals: sum[i..j] = prefix[j] - prefix[i-1]. The brute force was recomputing those totals it already had.","So at each end index we hold the running prefix already. The open question is what state lets us turn that one total into a count of all the windows ending here, without walking back over earlier positions."]},{"id":"pattern-quiz","chapter":"The idea","kind":"choice","source":"pattern-recognition","eyebrow":"Spot the pattern","title":"Which question counts the windows?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pattern-quiz-state","state":{"rows":[{"label":"nums","values":[1,0,1,0,1]},{"label":"prefix","values":[1,1,2,2,3],"changed":[0,1]}],"i":4,"prefix_sum":3,"goal":2,"needed":1}}]},"quiz":{"contract":"pattern-recognition-v1","question":"Which question counts the windows?","signalPrompt":"Walking left to right with a running prefix total, which question, answered in O(1), counts every goal-window ending at the current position?","options":[{"id":"count-earlier-prefixes","label":"How many earlier prefixes equal `prefix-goal`?","signal":"prefix[j] - prefix[i-1] = goal rearranges to prefix[i-1] = prefix[j] - goal.","rationale":"Each earlier position whose prefix equals `prefix-goal` starts one goal-window ending here. The same prefix can recur at several earlier positions, and each one is a separate start.","isCorrect":true},{"id":"count-the-ones","label":"How many 1s have I passed so far?","signal":"The running count of 1s is exactly the prefix sum here.","rationale":"That number is the prefix total, but a single total cannot say how many windows end here. The answer needs how many earlier totals sit goal below it.","isCorrect":false},{"id":"seen-before","label":"Has this prefix value appeared before?","signal":"Membership is one set lookup.","rationale":"Appeared is yes or no; the count needs how many earlier positions produced that total, because each position is a distinct window start.","isCorrect":false},{"id":"sorted-bait","label":"Can the array be sorted first?","signal":"Sorted data unlocks binary search.","rationale":"Sorting destroys contiguity: the subarrays being counted exist only in the original order.","isCorrect":false}],"missFeedback":"Rearrange the identity: a goal-window ending here needs an earlier prefix equal to `prefix-goal`. Count every matching earlier prefix."}},{"id":"approach-selection","chapter":"The idea","kind":"choice","source":"approach-selection","eyebrow":"Pick the approach","title":"Which approach turns that lookup question into one pass?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-selection-state","state":{"nums":[1,0,1,0,1],"i":4,"prefix_sum":3,"goal":2}}]}},{"id":"state-setup","chapter":"The idea","kind":"case-probe","eyebrow":"Read the state","title":"What do the two occurrences in prefix_counts[1] represent?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"state-setup-state","state":{"nums":[1,0,1,0,1],"i":4,"seen":{"0":1,"1":2,"2":2},"seenHighlight":1,"prefix_sum":3,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"summary":"The goal is 2, the current prefix is 3, and the needed earlier prefix is 3 - 2 = 1.","options":[{"id":"two-boundaries","label":"Two earlier boundaries where the running total was 1","rationale":"A prefix occurrence marks a boundary before a possible window. Each boundary with total 1 pairs with the current total 3 to form a different window summing to 2.","isCorrect":true},{"id":"two-array-values","label":"Two array elements whose value is 1","rationale":"The map records cumulative totals at boundaries. It does not count individual 1 values in the array.","isCorrect":false},{"id":"two-finished-windows","label":"Two goal-windows that were already counted earlier","rationale":"The occurrences are candidate left boundaries for windows ending at the current index. They do not describe windows that ended in a previous step.","isCorrect":false}],"answer":"They are two earlier boundaries where the running total was 1. Both pair with the current total 3, so they create two distinct windows ending here."},{"id":"zero-effect-probe","chapter":"The idea","kind":"case-probe","eyebrow":"Name the rule","title":"What does a 0 do to the running total?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"zero-effect-state","state":{"nums":[1,0,1,0,1],"i":1,"seen":{"0":1,"1":1},"seenHighlight":1,"prefix_sum":1,"count":0,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"summary":"At index 0 the total reached 1. At index 1 the element is 0.","options":[{"id":"recurs","label":"It leaves the total at 1, so prefix 1 is recorded a second time","rationale":"Adding 0 changes nothing, so the same total recurs. prefix_counts[1] becomes 2: two earlier positions now share that total.","isCorrect":true},{"id":"increments","label":"It nudges the total up to 2 like any other element","rationale":"Only a 1 raises the total. A 0 holds it in place, which is exactly why prefixes repeat in this problem.","isCorrect":false},{"id":"resets","label":"It resets the running total back toward 0","rationale":"The prefix sum only ever accumulates; a 0 adds nothing rather than subtracting. The total never goes down here.","isCorrect":false}],"answer":"A 0 holds the total steady, so the same prefix is recorded again. A prefix that occurs twice is two separate window starts waiting for a later match."},{"id":"dry-run-setup","chapter":"Trace","kind":"info","eyebrow":"Watch it move","title":"One seed, then the walk","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"dry-run-start","state":{"nums":[1,0,1,0,1],"seen":{"0":1},"prefix_sum":0,"count":0,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"body":["The map starts as {0: 1} before anything is read: the empty prefix, the total of zero elements, has occurred once. It is the left side of every window that starts at index 0.","Each step: extend `prefix_sum`, look up `prefix_sum-goal`, add whatever count comes back, then record the new total."]},{"id":"trace","chapter":"Trace","kind":"dry-run","source":"trace-example","eyebrow":"Trace the count","title":"Trace the prefix walk","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"first-match","state":{"nums":[1,0,1,0,1],"i":2,"seen":{"0":1,"1":2,"2":1},"seenHighlight":0,"prefix_sum":2,"count":1,"goal":2,"labels":{"seen":"prefix_counts"}}},{"id":"zero-rides","state":{"nums":[1,0,1,0,1],"i":3,"seen":{"0":1,"1":2,"2":2},"seenHighlight":0,"prefix_sum":2,"count":2,"goal":2,"labels":{"seen":"prefix_counts"}}},{"id":"double-hit","state":{"nums":[1,0,1,0,1],"i":4,"seen":{"0":1,"1":2,"2":2,"3":1},"seenHighlight":1,"prefix_sum":3,"count":4,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"beats":[{"id":"first-match","title":"Which window did the first hit count?","summary":"The 1 at index 2 brings prefix_sum to 2.","prompt":"A 1 lifts the running total to 2; the lookup key is 2 - 2 = 0.","options":[{"id":"from-front","label":"[0..2], the window starting at index 0, whose left side is the empty prefix","rationale":"prefix 2 minus the empty prefix 0 is the whole front [1, 0, 1], which holds two 1s. Without the {0: 1} seed this window would be invisible.","isCorrect":true},{"id":"just-current","label":"[2..2], the element we are standing on","rationale":"nums[2] alone is a single 1, sum 1, not 2. The hit’s earlier prefix is the empty one, so the window reaches the front.","isCorrect":false},{"id":"phantom","label":"Nothing real, 0 was never an actual total","rationale":"It is the total of the empty front, and exactly the left side a window starting at index 0 needs. The seed is bookkeeping for a real case.","isCorrect":false}],"answer":"count becomes 1 for [0..2]. The seed exists so windows touching the left edge get counted."},{"id":"zero-rides","title":"What did the 0 at index 3 change?","summary":"The element at index 3 is a 0, so prefix_sum holds at 2.","prompt":"A 0 leaves the running total at 2; the lookup key is again 0.","options":[{"id":"extends-window","label":"It counts [0..3], the same front stretch with a trailing 0 riding along","rationale":"Sum is still two 1s, so [0..3] is a new valid window, and prefix 2 gets recorded a second time for future matches.","isCorrect":true},{"id":"no-effect","label":"Nothing, a 0 cannot create a new subarray","rationale":"A trailing 0 makes a distinct stretch with the same sum, so it is a separate valid window, counted here.","isCorrect":false},{"id":"undo","label":"It cancels the previous hit","rationale":"The running count only grows. Each match adds; nothing in the scan removes an earlier window.","isCorrect":false}],"answer":"count becomes 2 for [0..3], and prefix 2 is now stored twice. Zeros multiply windows by riding along an unchanged total."},{"id":"double-hit","title":"What should the lookup for prefix 1 contribute?","summary":"The 1 at index 4 brings prefix_sum to 3; the lookup key is 3 - 2 = 1.","prompt":"The running total reaches 3, so the lookup asks for earlier prefix 1.","options":[{"id":"two-starts","label":"prefix 1 occurred at two earlier positions, each one a separate window start","rationale":"prefix_counts[1] is 2: the 1 at index 0 and the 0 at index 1 both left the total at 1. Two left edges means two windows ending here, [1..4] and [2..4].","isCorrect":true},{"id":"always-one","label":"It should add 1, one match is one window","rationale":"Adding 1 here gives a final count of 3, but the answer is 4. The map value is the multiplicity, and a recurring prefix is several starts.","isCorrect":false},{"id":"faster","label":"Adding the stored value is just faster than looping","rationale":"Same speed; this is correctness. Each occurrence of the needed prefix is a genuinely distinct window.","isCorrect":false}],"answer":"count += prefix_counts[1] adds 2, reaching 4. The zero at index 1 manufactured the second start, which is why counts beat flags."}]},{"id":"set-vs-count-pitfall","chapter":"Trace","kind":"pitfall","eyebrow":"Spot the trap","title":"Does it matter when the current prefix is recorded?","summary":"The map update and the lookup are two lines inside the loop, and either order runs without error. Recording the current prefix first looks harmless, the same keys end up in the map. Watch it on nums = [0, 0], goal = 0.","workspacePanel":"trace","pitfall":"The code below records the current prefix into the map before it does the needed-prefix lookup.","whyItMatters":"Look up before you record. Recording first lets the current prefix answer its own lookup, so prefix minus prefix counts a span of zero elements. On goal = 0, where the lookup key equals the current prefix, that phantom fires on every index.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"count = 0\nprefix_sum = 0\nprefix_counts = {0: 1}\nfor num in nums:\n    prefix_sum += num\n    prefix_counts[prefix_sum] = prefix_counts.get(prefix_sum, 0) + 1\n    needed = prefix_sum - goal\n    if needed in prefix_counts:\n        count += prefix_counts[needed]\nreturn count","steps":[{"id":"record-first","title":"Record the current prefix first","codeLine":6,"summary":"nums = [0, 0], goal = 0. At index 0 the 0 holds prefix_sum at 0, and the map update bumps prefix_counts[0] to 2 before any lookup.","state":{"nums":[0,0],"i":0,"seen":{"0":2},"labels":{"seen":"prefix_counts"}}},{"id":"self-match","title":"The prefix answers its own lookup","codeLine":9,"summary":"needed = 0 - 0 = 0, and prefix_counts[0] is now 2, so the lookup adds 2. One of those is the empty span from this prefix back to itself.","state":{"nums":[0,0],"i":0,"seen":{"0":2},"seenHighlight":0,"labels":{"seen":"prefix_counts"}}},{"id":"phantom","title":"Two phantom empties, count too high","codeLine":9,"summary":"Index 1 repeats it: prefix_counts[0] becomes 3, the lookup adds 3, count ends at 5. The real answer is 3: [0], [0], [0..1].","state":{"nums":[0,0],"i":1,"seen":{"0":3},"seenHighlight":0,"labels":{"seen":"prefix_counts"}}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"let count = 0;\nlet prefixSum = 0;\nconst prefixCounts = new Map();\nprefixCounts.set(0, 1);\nfor (const num of nums) {\n    prefixSum += num;\n    prefixCounts.set(prefixSum, (prefixCounts.has(prefixSum) ? prefixCounts.get(prefixSum) : 0) + 1);\n    const needed = prefixSum - goal;\n    if (prefixCounts.has(needed)) {\n        count += prefixCounts.get(needed);\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"let count = 0;\nlet prefixSum = 0;\nconst prefixCounts: Map<number, number> = new Map();\nprefixCounts.set(0, 1);\nfor (const num of nums) {\n    prefixSum += num;\n    prefixCounts.set(prefixSum, (prefixCounts.has(prefixSum) ? prefixCounts.get(prefixSum)! : 0) + 1);\n    const needed = prefixSum - goal;\n    if (prefixCounts.has(needed)) {\n        count += prefixCounts.get(needed)!;\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int count = 0;\nint prefixSum = 0;\nMap<Integer, Integer> prefixCounts = new HashMap<Integer, Integer>();\nprefixCounts.put(0, 1);\nfor (Integer num : nums) {\n    prefixSum += num;\n    prefixCounts.put(prefixSum, (prefixCounts.getOrDefault(prefixSum, 0) + 1));\n    int needed = prefixSum - goal;\n    if (prefixCounts.containsKey(needed)) {\n        count += prefixCounts.get(needed);\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int count = 0;\nint prefixSum = 0;\nDictionary<int, int> prefixCounts = new();\nprefixCounts[0] = 1;\nforeach (int num in nums) {\n    prefixSum += num;\n    prefixCounts[prefixSum] = (prefixCounts.ContainsKey(prefixSum) ? prefixCounts[prefixSum] : 0) + 1;\n    int needed = prefixSum - goal;\n    if (prefixCounts.ContainsKey(needed)) {\n        count += prefixCounts[needed];\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int count = 0;\nint prefix_sum = 0;\nunordered_map<int, int> prefix_counts;\nprefix_counts[0] = 1;\nfor (int num : nums) {\n    prefix_sum += num;\n    prefix_counts[prefix_sum] += 1;\n    int needed = prefix_sum - goal;\n    if (prefix_counts.count(needed)) {\n        count += prefix_counts.at(needed);\n    }\n}\nreturn count;","lineMap":{"1":1,"2":2,"3":3,"4":5,"5":6,"6":7,"7":8,"8":9,"9":10,"10":13},"statementBundles":{"3":{"startLine":3,"endLine":4},"9":{"startLine":10,"endLine":12}}}}}},{"id":"edge-case-intro","chapter":"Edge cases","kind":"info","eyebrow":"Try to break it","title":"Two inputs that lean on the map","ctaLabel":"Check edge cases","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-baseline","state":{"nums":[0,0,0],"seen":{"0":1},"prefix_sum":0,"count":0,"goal":0,"labels":{"seen":"prefix_counts"}}}]},"body":["Try nums = [0, 0, 0] with goal = 0, and nums = [1, 0, 1] with goal = 2.","Walk each one through the lookup and decide what the map has to carry."]},{"id":"goal-zero-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"On all zeros with goal 0, what does each step add?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"goal-zero-state","state":{"nums":[0,0,0],"i":2,"seen":{"0":3},"seenHighlight":0,"prefix_sum":0,"count":3,"goal":0,"labels":{"seen":"prefix_counts"}}}]},"summary":"nums = [0, 0, 0], goal = 0. The running total never moves from 0.","options":[{"id":"climbing-count","label":"It adds the current count of prefix 0: 1, then 2, then 3, for a total of 6","rationale":"Each index looks up prefix 0 and gets however many earlier positions reached it. Those grow 1, 2, 3, so the answer is 1 + 2 + 3 = 6, every non-empty window of [0, 0, 0].","isCorrect":true},{"id":"always-one","label":"It adds 1 each step, for a total of 3","rationale":"Adding 1 per hit ignores that prefix 0 was reached by several earlier positions. A flag would give 3; the count of 0s gives 6, which is the true number of zero windows.","isCorrect":false},{"id":"nothing","label":"Nothing, a window of all zeros sums to 0 but goal is 0 so it does not count","rationale":"A sum of 0 is exactly goal 0, so every zero window is valid. The all-zero case is where the count of repeated prefixes does the most work.","isCorrect":false}],"answer":"Each step adds the running count of prefix 0, so the total is 1 + 2 + 3 = 6. Repeated prefixes are why the map stores counts."},{"id":"starts-at-zero-probe","chapter":"Edge cases","kind":"case-probe","eyebrow":"Force a decision","title":"Where does the front-edge window come from?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"starts-at-zero-state","state":{"nums":[1,0,1],"i":2,"seen":{"0":1,"1":2,"2":1},"seenHighlight":0,"prefix_sum":2,"count":1,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"summary":"nums = [1, 0, 1], goal = 2, at index 2 with prefix_sum = 2. The only valid window is [0..2], which starts at the very front.","options":[{"id":"seed-supplies","label":"The {0: 1} seed: it is the left side of any window starting at index 0","rationale":"The lookup asks for prefix 2 - 2 = 0, and only the seeded empty prefix carries that total. Without the seed, [0..2] would never be counted.","isCorrect":true},{"id":"first-element","label":"The entry recorded when the first element was read","rationale":"After index 0 the recorded prefix is 1, not 0. The needed total 0 exists only because the map was seeded before the scan.","isCorrect":false},{"id":"special-branch","label":"A special case for subarrays that touch index 0","rationale":"No branch is needed: the seed makes the front edge an ordinary lookup, identical to every other position.","isCorrect":false}],"answer":"The seeded prefix 0 is the empty front. It turns \"starts at index 0\" into a normal hit, no special case required."},{"id":"ready-to-code","chapter":"Code","kind":"info","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Most of it is one plain scan; the {0: 1} seed and looking up before recording are what carry the correctness.","ctaLabel":"Start coding","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"nums":[1,0,1,0,1],"seen":{"0":1},"prefix_sum":0,"count":0,"goal":2,"labels":{"seen":"prefix_counts"}}}]},"body":["Seed the map with the empty prefix, then make one pass: extend the running total, add the count of earlier prefixes equal to total minus goal, and record the new total."]},{"id":"coding","chapter":"Code","kind":"coding","source":"coding-checkpoints","eyebrow":"Code the rule","title":"Build the prefix counter","summary":"Now write it: seed the map with {0: 1}, then scan once, adding each number into the running total, looking up total minus goal before you record the new total, adding back whatever count that lookup returns, then return the total.","workspacePanel":"code"},{"id":"complete","chapter":"Code","kind":"complete","eyebrow":"Take it with you","title":"What to carry forward","summary":"Window sums are prefix differences; in a binary array, zeros make the counting do the work.","workspacePanel":"code","body":["This is a hash-map counting move: the lookup asks how many earlier prefixes can start a valid window.","The binary twist lives in the zeros: a 0 holds the prefix steady, so a total recurs and stands for several window starts. That is why the map stores counts."],"takeaways":[{"title":"Rearrange, then look up","body":"sum[i..j] = goal becomes prefix[i-1] = prefix[j] - goal. Counting windows becomes counting earlier prefixes equal to `prefix-goal`."},{"title":"Zeros are why counts beat flags","body":"A 0 leaves the prefix unchanged, so the same total marks several earlier starts. A set would collapse them; the count map keeps the multiplicity."},{"title":"Two tiny lines hold correctness","body":"The {0: 1} seed counts windows touching the front edge, and looking up before recording stops a prefix from matching itself when goal = 0."},{"title":"One pass, linear space","body":"One scan makes the time O(n), improving on the O(n^2) nested loops; the tradeoff is O(n) space for up to n + 1 prefix totals, where the brute force used only O(1)."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
