Count Number of Nice Subarrays

Pattern: Sliding window: variable size

medium

Treat odd numbers as 1 and even ones as 0. Then it is Binary Subarrays With Sum. Count windows with at most k odds and subtract those with at most k - 1.

The problem

You are given an array of positive whole numbers and a number k. A block of neighbouring elements is nice if exactly k of its numbers are odd. Count the nice blocks. For example, [1, 1, 2, 1, 1] with k = 3 has 2 nice blocks, and [2, 2, 2, 1, 2, 2, 1, 2, 2, 2] with k = 2 has 16.

The function name numberOfSubarrays matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Does the actual value of an even number matter? Of an odd number?
  • Rewrite each number as 1 if odd and 0 if even. What is the question now?
  • Have you seen that question in this pattern before?

Hints

    Brute force, and why it fails

    Count odds in every block with a running count: O(n²). Two windows give O(n).

    The key insight

    Once each number is reduced to odd or even, this is Binary Subarrays With Sum. The "exactly = at most k minus at most k - 1" trick solves both.

    Dry run

    10 
    11 
    02 
    13 
    14 
    k3

    nums = [1, 1, 2, 1, 1] and k = 3. As odd or even this reads 1, 1, 0, 1, 1. Count windows with at most 3 odds first.

    Step 1 of 4

    The plan

    function atMost(g):
        if g < 0: return 0
        left = 0, odd = 0, count = 0
        for right from 0 to n - 1:
            odd = odd + nums[right] % 2
            while odd > g:
                odd = odd - nums[left] % 2
                left = left + 1
            count = count + (right - left + 1)
        return count
    
    return atMost(k) - atMost(k - 1)
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    Two O(n) passes with counters only.

    Edge cases

    • No odd numbers and k at least 1: 0.
    • A single odd number with k = 1: 1.
    • Many evens around the odds: each run of evens on either side multiplies the choices, which is why the second example has 16.
    I've built my logic, show the code

    Java

    class Solution {
        public int numberOfSubarrays(int[] nums, int k) {
            return atMost(nums, k) - atMost(nums, k - 1);   // exactly k odds = at most k minus at most k - 1
        }
    
        private int atMost(int[] nums, int k) {
            if (k < 0) return 0;
            int left = 0, odd = 0, count = 0;
            for (int right = 0; right < nums.length; right++) {
                odd += nums[right] % 2;
                while (odd > k) {
                    odd -= nums[left] % 2;
                    left++;
                }
                count += right - left + 1;          // every subarray ending at right and starting in the window
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int numberOfSubarrays(vector<int>& nums, int k) {
            return atMost(nums, k) - atMost(nums, k - 1);   // exactly k odds = at most k minus at most k - 1
        }
    
        int atMost(vector<int>& nums, int k) {
            if (k < 0) return 0;
            int left = 0, odd = 0, count = 0;
            for (int right = 0; right < static_cast<int>(nums.size()); right++) {
                odd += nums[right] % 2;
                while (odd > k) {
                    odd -= nums[left] % 2;
                    left++;
                }
                count += right - left + 1;          // every subarray ending at right and starting in the window
            }
            return count;
        }
    };

    Python

    class Solution:
        def numberOfSubarrays(self, nums: list[int], k: int) -> int:
            return self.at_most(nums, k) - self.at_most(nums, k - 1)   # exactly k odds = at most k minus at most k - 1
    
        def at_most(self, nums: list[int], k: int) -> int:
            if k < 0:
                return 0
            left = odd = count = 0
            for right, v in enumerate(nums):
                odd += v % 2
                while odd > k:
                    odd -= nums[left] % 2
                    left += 1
                count += right - left + 1           # every subarray ending at right and starting in the window
            return count

    Common mistakes

    • Using nums[i] % 2 == 1 with negative numbers in other languages. The values here are positive, but % 2 on a negative odd number gives -1 in Java and C++.
    • Shrinking until the window has exactly k odds, which skips blocks with extra evens at the start.
    • Adding 1 per step instead of right - left + 1.

    Similar problems