{"id":924,"date":"2025-08-20T13:05:52","date_gmt":"2025-08-20T07:35:52","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=924"},"modified":"2025-08-20T13:24:04","modified_gmt":"2025-08-20T07:54:04","slug":"binary-subarrays-with-sum","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/","title":{"rendered":"Binary Subarrays With Sum | Leetcode 930 | Optimal Prefix\/Sliding Window Trick"},"content":{"rendered":"\n<p>The problem&nbsp;<strong>\u201cBinary Subarrays With Sum\u201d<\/strong>&nbsp;asks to count the number of contiguous subarrays in a binary array&nbsp;<code>nums<\/code>&nbsp;whose sum equals a given&nbsp;<strong>goal<\/strong>. Because the array is binary (only 0s and 1s), we can exploit special properties to achieve an&nbsp;<strong>O(n)<\/strong>&nbsp;solution using a clever&nbsp;<strong>at-most<\/strong>&nbsp;trick.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/binary-subarrays-with-sum\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>Given a binary array&nbsp;<code>nums<\/code>&nbsp;and an integer&nbsp;<code>goal<\/code>, return&nbsp;<em>the number of non-empty&nbsp;<strong>subarrays<\/strong>&nbsp;with a sum<\/em>&nbsp;<code>goal<\/code>.<\/p>\n\n\n\n<p>A&nbsp;<strong>subarray<\/strong>&nbsp;is a contiguous part of the array.<\/p>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [1,0,1,0,1], goal = 2<br><strong>Output:<\/strong> 4<br><strong>Explanation:<\/strong> The 4 subarrays are bolded and underlined below:<br>[<strong>1,0,1<\/strong>,0,1]<br>[<strong>1,0,1,0<\/strong>,1]<br>[1,<strong>0,1,0,1<\/strong>]<br>[1,0,<strong>1,0,1<\/strong>]<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [0,0,0,0,0], goal = 0<br><strong>Output:<\/strong> 15<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4<\/sup><\/code><\/li>\n\n\n\n<li><code>nums[i]<\/code>&nbsp;is either&nbsp;<code>0<\/code>&nbsp;or&nbsp;<code>1<\/code>.<\/li>\n\n\n\n<li><code>0 &lt;= goal &lt;= nums.length<\/code><\/li>\n<\/ul>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-6067b89c-2d54-4ad4-a253-f73089a51038\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"true\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#0-brute-force-enumerate-all-starts-\" style=\"\">Brute Force (Enumerate All Starts)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#1-intuition-and-approach-\" style=\"\">Intuition and Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#2-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#3-why-it-works-\" style=\"\">Why It Works<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#4-time-and-space-complexity-\" style=\"\">Time and Space Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#5-optimal-at-most-trick-with-sliding-window-two-pointers-\" style=\"\">Optimal (At-Most Trick with Sliding Window \/ Two Pointers)<\/a><ul><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#6-core-insight-\" style=\"\">Core Insight<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#7-helper-count-subarrays-with-sum-%E2%89%A4-goal-\" style=\"\">Helper: Count subarrays with sum \u2264 goal<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#8-code\" style=\"\">Code<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#9-why-this-is-correct-\" style=\"\">Why This Is Correct<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#10-edge-cases-\" style=\"\">Edge Cases<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#11-time-and-space-complexity-\" style=\"\">Time and Space Complexity<\/a><\/li><\/ul><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#12-alternative-note-prefix-sum-hash-map\" style=\"\">Alternative Note: Prefix Sum + Hash Map<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/binary-subarrays-with-sum\/#13-final-takeaway\" style=\"\">Final Takeaway<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"0-brute-force-enumerate-all-starts-\">Brute Force (<strong>Enumerate All Starts<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach-\"><strong>Intuition and Approach<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For each start index&nbsp;<code>i<\/code>, expand the end index&nbsp;<code>j<\/code>, maintain a running&nbsp;<strong>total<\/strong>.<\/li>\n\n\n\n<li>If&nbsp;<code>total &gt; goal<\/code>, break early (since adding more 0\/1 can only increase or keep the same).<\/li>\n\n\n\n<li>If&nbsp;<code>total == goal<\/code>, increment the&nbsp;<strong>count<\/strong>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def numSubarraysWithSum(self, nums: List[int], goal: int) -&gt; int:\n        count = 0\n        n = len(nums)\n        for i in range(n):\n            total = 0\n            for j in range(i, n):\n                total += nums[j]\n                if total &gt; goal:\n                    break\n                if total == goal:\n                    count += 1\n        return count\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numSubarraysWithSum<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">goal<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            total = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> j <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(i, n):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                total += nums[j]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> total &gt; goal:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">break<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> total == goal:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    count += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-why-it-works-\"><strong>Why It Works<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Sums in a binary array are non-decreasing as the window expands, enabling an&nbsp;<strong>early break<\/strong>&nbsp;once&nbsp;<code>total &gt; goal<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-time-and-space-complexity-\"><strong>Time and Space Complexity<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>&nbsp;O(n^2) in worst case<\/li>\n\n\n\n<li><strong>Space:<\/strong>&nbsp;O(1)<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-optimal-at-most-trick-with-sliding-window-two-pointers-\">Optimal (<strong>At-Most Trick with Sliding Window \/ Two Pointers<\/strong>)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"6-core-insight-\"><strong>Core Insight<\/strong><\/h3>\n\n\n\n<p>For binary arrays, the count of subarrays with sum&nbsp;<strong>exactly<\/strong>&nbsp;<code>goal<\/code>&nbsp;equals:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>count( sum \u2264 goal ) \u2212 count( sum \u2264 goal\u22121 )<\/li>\n<\/ul>\n\n\n\n<p>This works because with only 0s and 1s, as&nbsp;<code>goal<\/code>&nbsp;increases, every new valid subarray adds to the count monotonically. So, we can compute a helper that returns number of subarrays with sum at most&nbsp;<code>X<\/code>, then subtract.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"7-helper-count-subarrays-with-sum-%E2%89%A4-goal-\"><strong>Helper: Count subarrays with sum \u2264 goal<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Maintain a window&nbsp;<code>[left..right]<\/code>&nbsp;and running&nbsp;<strong>Sum<\/strong>.<\/li>\n\n\n\n<li>Expand&nbsp;<code>right<\/code>, add&nbsp;<code>nums[right]<\/code>.<\/li>\n\n\n\n<li>While&nbsp;<code>Sum &gt; goal<\/code>, shrink from&nbsp;<code>left<\/code>, subtracting&nbsp;<code>nums[left]<\/code>.<\/li>\n\n\n\n<li>At each step, all subarrays ending at&nbsp;<code>right<\/code>&nbsp;and starting from any index in&nbsp;<code>[left..right]<\/code>&nbsp;are valid, contributing&nbsp;<code>(right - left + 1)<\/code>&nbsp;to the count.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"8-code\">Code<\/h3>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro cbp-has-line-numbers\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;--cbp-line-number-color:#D4D4D4;--cbp-line-number-width:calc(2 * 0.6 * .875rem);line-height:1.5rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"class Solution:\n    def countSubArrayLessThanOrEqualToGoal(self, nums, goal):\n        if goal &lt; 0:\n            return 0\n        count = 0\n        n = len(nums)\n        left = 0\n        right = 0\n        Sum = 0\n        while right &lt; n:\n            Sum += nums[right]\n            while Sum &gt; goal:\n                Sum -= nums[left]\n                left += 1\n            count = count + ((right - left) + 1)\n            right += 1\n        return count\n\n    def numSubarraysWithSum(self, nums: List[int], goal: int) -&gt; int:\n        return self.countSubArrayLessThanOrEqualToGoal(\n            nums, goal\n        ) - self.countSubArrayLessThanOrEqualToGoal(nums, goal - 1)\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">countSubArrayLessThanOrEqualToGoal<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">goal<\/span><span style=\"color: #D4D4D4\">):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> goal &lt; <\/span><span style=\"color: #B5CEA8\">0<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        count = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        n = <\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(nums)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        left = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        right = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        Sum = <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> right &lt; n:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            Sum += nums[right]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> Sum &gt; goal:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                Sum -= nums[left]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                left += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            count = count + ((right - left) + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            right += <\/span><span style=\"color: #B5CEA8\">1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> count<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">numSubarraysWithSum<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">nums<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">], <\/span><span style=\"color: #9CDCFE\">goal<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.countSubArrayLessThanOrEqualToGoal(<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            nums, goal<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ) - <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.countSubArrayLessThanOrEqualToGoal(nums, goal - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"9-why-this-is-correct-\"><strong>Why This Is Correct<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>In a binary array, the number of subarrays with sum at most&nbsp;<code>goal<\/code>&nbsp;can be counted with a&nbsp;<strong>single-pass sliding window<\/strong>&nbsp;because as the window grows, the sum increases by at most 1 per step.<\/li>\n\n\n\n<li>Therefore, exactly-<code>goal<\/code>&nbsp;counts are obtained by subtracting at-most-<code>goal-1<\/code>&nbsp;from at-most-<code>goal<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"10-edge-cases-\"><strong>Edge Cases<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>When&nbsp;<code>goal &lt; 0<\/code>, there are&nbsp;<strong>no<\/strong>&nbsp;valid subarrays, so the helper returns&nbsp;<strong>0<\/strong>&nbsp;(already handled).<\/li>\n\n\n\n<li>Handles&nbsp;<code>goal = 0<\/code>&nbsp;naturally: at-most-0 counts all-zero windows; at-most-(-1) is 0; difference yields exact 0-sum subarrays.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"11-time-and-space-complexity-\"><strong>Time and Space Complexity<\/strong><\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time:<\/strong>&nbsp;O(n) &#8211; each pointer moves at most<strong> n<\/strong> steps<\/li>\n\n\n\n<li><strong>Space:<\/strong>&nbsp;O(1)<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"12-alternative-note-prefix-sum-hash-map\">Alternative Note: Prefix Sum + Hash Map<\/h2>\n\n\n\n<p>Another common exact-count method uses a&nbsp;<strong>prefix sum<\/strong>&nbsp;and a&nbsp;<strong>frequency map<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For each index, compute running sum&nbsp;<code>pref<\/code>.<\/li>\n\n\n\n<li>Subarrays with sum&nbsp;<code>goal<\/code>&nbsp;ending at current index equal the count of&nbsp;<code>pref - goal<\/code>&nbsp;seen so far.<\/li>\n\n\n\n<li>Update map with current&nbsp;<code>pref<\/code>.<\/li>\n\n\n\n<li>This also yields&nbsp;<strong>O(n)<\/strong>&nbsp;time and&nbsp;<strong>O(n)<\/strong>&nbsp;space.<\/li>\n<\/ul>\n\n\n\n<p>However, the provided solution uses the elegant&nbsp;<strong>at-most trick<\/strong>&nbsp;tailored for&nbsp;<strong>binary<\/strong>&nbsp;arrays, achieving&nbsp;<strong>O(n)<\/strong>&nbsp;time and&nbsp;<strong>O(1)<\/strong>&nbsp;space.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"13-final-takeaway\">Final Takeaway<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use&nbsp;<strong>Brute Force<\/strong>&nbsp;for small inputs to build intuition.<\/li>\n\n\n\n<li>For production, prefer the&nbsp;<strong>at-most sliding window trick<\/strong>:<br>exact = atMost(goal) \u2212 atMost(goal\u22121), which is both&nbsp;<strong>clean<\/strong>&nbsp;and&nbsp;<strong>linear-time<\/strong>&nbsp;for binary arrays.<\/li>\n\n\n\n<li>Remember this pattern for other \u201cexact sum\u201d problems on binary arrays &#8211; it\u2019s a powerful and reusable technique.<\/li>\n<\/ul>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\" target=\"_blank\" rel=\"noreferrer noopener\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\" target=\"_blank\" rel=\"noreferrer noopener\">+91-9712928220<\/a>.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The problem&nbsp;\u201cBinary Subarrays With Sum\u201d&nbsp;asks to count the number of contiguous subarrays in a binary array&nbsp;nums&nbsp;whose sum equals a given&nbsp;goal. Because the array is binary (only 0s and 1s), we can exploit special properties to achieve an&nbsp;O(n)&nbsp;solution using a clever&nbsp;at-most&nbsp;trick. Here&#8217;s the [Problem Link] to begin with. Given a binary array&nbsp;nums&nbsp;and an integer&nbsp;goal, return&nbsp;the number<\/p>\n","protected":false},"author":1,"featured_media":925,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,6],"tags":[18,40],"class_list":{"0":"post-924","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-intermediate","9":"tag-hard","10":"tag-sliding-window-and-two-pointers"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/binary-subarrays-with-sum-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/924","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=924"}],"version-history":[{"count":2,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/924\/revisions"}],"predecessor-version":[{"id":928,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/924\/revisions\/928"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/925"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=924"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=924"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=924"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}