{"id":927,"date":"2025-08-20T13:27:25","date_gmt":"2025-08-20T07:57:25","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=927"},"modified":"2025-08-20T13:27:27","modified_gmt":"2025-08-20T07:57:27","slug":"count-number-of-nice-subarrays","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/count-number-of-nice-subarrays\/","title":{"rendered":"Count Number of Nice Subarrays | Leetcode 1248"},"content":{"rendered":"\n<p>The problem\u00a0\u201cCount Number\u00a0of Nice Subarrays\u201d asks: given an integer\u00a0array nums and\u00a0an integer k, count the number\u00a0of contiguous\u00a0subarrays that\u00a0contain exactly\u00a0k odd numbers. This is a perfect\u00a0use case for\u00a0the at-most trick: count subarrays with\u00a0at most k odds, subtract subarrays with at\u00a0most k\u22121 odds. The difference\u00a0gives exactly\u00a0k odds.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/count-number-of-nice-subarrays\/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 an array of integers&nbsp;<code>nums<\/code>&nbsp;and an integer&nbsp;<code>k<\/code>. A continuous subarray is called&nbsp;<strong>nice<\/strong>&nbsp;if there are&nbsp;<code>k<\/code>&nbsp;odd numbers on it.<\/p>\n\n\n\n<p>Return&nbsp;<em>the number of&nbsp;<strong>nice<\/strong>&nbsp;sub-arrays<\/em>.<\/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,1,2,1,1], k = 3<br><strong>Output:<\/strong> 2<br><strong>Explanation:<\/strong> The only sub-arrays with 3 odd numbers are [1,1,2,1] and [1,2,1,1].<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [2,4,6], k = 1<br><strong>Output:<\/strong> 0<br><strong>Explanation:<\/strong> There are no odd numbers in the array.<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Input:<\/strong> nums = [2,2,2,1,2,2,1,2,2,2], k = 2<br><strong>Output:<\/strong> 16<\/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;= 50000<\/code><\/li>\n\n\n\n<li><code>1 &lt;= nums[i] &lt;= 10^5<\/code><\/li>\n\n\n\n<li><code>1 &lt;= k &lt;= nums.length<\/code><\/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=\"0-optimal-solution-sliding-window-at-most-%E2%86%92-exact\">Optimal Solution: Sliding Window (At-Most \u2192 Exact)<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"1-intuition-and-approach\">Intuition and Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Maintain a window <strong>[left..right]<\/strong> and track <strong>Sum <\/strong>= number of odds in the window.<\/li>\n\n\n\n<li>Expand right; add <strong>nums[right] % 2<\/strong> to <strong>Sum<\/strong>.<\/li>\n\n\n\n<li>While<strong> Sum > goal<\/strong>, shrink from the <strong>left<\/strong>, subtracting <strong>nums[left] % 2<\/strong>, and increment <strong>left<\/strong>.<\/li>\n\n\n\n<li>For each <strong>right<\/strong>, after enforcing <strong>Sum \u2264 goal<\/strong>, all subarrays ending at right and starting from any index in [left..right] are valid, contributing <strong>(right \u2212 left + 1)<\/strong> to the count.<\/li>\n\n\n\n<li>Do this once for <strong>goal = k<\/strong> and once for <strong>goal = k\u22121;<\/strong> the difference is the number of subarrays with exactly <strong>k <\/strong>odds.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"2-code-kept-exactly-as-provided-minimal-formatted-comments-added\">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            # Add 1 if nums[right] is odd, else add 0\n            Sum += nums[right] % 2\n            # Shrink window until number of odds &lt;= goal\n            while Sum &gt; goal:\n                Sum -= nums[left] % 2\n                left += 1\n            # All subarrays ending at right and starting from [left..right] are valid\n            count = count + ((right - left) + 1)\n            right += 1\n        return count\n\n    def numberOfSubarrays(self, nums: List[int], k: int) -&gt; int:\n        return self.countSubArrayLessThanOrEqualToGoal(\n            nums, k\n        ) - self.countSubArrayLessThanOrEqualToGoal(nums, k - 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\">            <\/span><span style=\"color: #6A9955\"># Add 1 if nums[right] is odd, else add 0<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            Sum += nums[right] % <\/span><span style=\"color: #B5CEA8\">2<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># Shrink window until number of odds &lt;= goal<\/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 style=\"color: #B5CEA8\">2<\/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\">            <\/span><span style=\"color: #6A9955\"># All subarrays ending at right and starting from [left..right] are valid<\/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\">numberOfSubarrays<\/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\">k<\/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, k<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        ) - <\/span><span style=\"color: #569CD6\">self<\/span><span style=\"color: #D4D4D4\">.countSubArrayLessThanOrEqualToGoal(nums, k - <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">)<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"3-why-this-works\">Why This Works<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The window always satisfies \u201cnumber of odds \u2264 goal.\u201d<\/li>\n\n\n\n<li>For each right, once the window is valid, every start position from left to right yields a valid subarray, hence (right \u2212 left + 1) contributions.<\/li>\n\n\n\n<li>exact K = atMost(K) \u2212 atMost(K\u22121) is a standard identity that converts exact counting into two linear at-most counts.<\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"4-complexity\">Complexity<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time<\/strong>: O(n) &#8211; each index is visited at most twice (once by right, once by left).<\/li>\n\n\n\n<li><strong>Space<\/strong>: O(1) &#8211; constant auxiliary variables.<\/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=\"6-tips-and-edge-cases\">Tips and Edge Cases<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>If k = 0, answer counts subarrays with zero odd numbers (i.e., all-even subarrays); the formula still works because atMost(\u22121) returns 0 by guard.<\/li>\n\n\n\n<li>The method is robust for any non-negative k and any integers in nums\u2014only odd\/even matters.<\/li>\n\n\n\n<li>If you prefer prefix-sum + hashmap, you can map odds to 1, evens to 0, and count subarrays with sum k in O(n) time but O(n) space. The sliding-window at-most trick achieves O(1) space.<\/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=\"7-takeaway\">Takeaway<\/h2>\n\n\n\n<p>Transforming the array into oddness (0\/1) and using the identity exact K = atMost(K) \u2212 atMost(K\u22121) lets you solve \u201cCount Number of Nice Subarrays\u201d in a clean, linear-time, constant-space manner\u2014ideal for interviews and production.<\/p>\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\u00a0\u201cCount Number\u00a0of Nice Subarrays\u201d asks: given an integer\u00a0array nums and\u00a0an integer k, count the number\u00a0of contiguous\u00a0subarrays that\u00a0contain exactly\u00a0k odd numbers. This is a perfect\u00a0use case for\u00a0the at-most trick: count subarrays with\u00a0at most k odds, subtract subarrays with at\u00a0most k\u22121 odds. The difference\u00a0gives exactly\u00a0k odds. Here&#8217;s the [Problem Link] to begin with. Given an array<\/p>\n","protected":false},"author":1,"featured_media":929,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[18,40],"class_list":{"0":"post-927","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-hard","10":"tag-sliding-window-and-two-pointers"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/08\/count-number-of-nice-subarrays-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\/927","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=927"}],"version-history":[{"count":1,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/927\/revisions"}],"predecessor-version":[{"id":930,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/927\/revisions\/930"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/929"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=927"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=927"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=927"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}