712148. Count Subarray with k odds

Medium

Here is a detailed Markdown blog post for the GeeksforGeeks problem "Count Subarray with k odds":

Count Subarray with k odds

Summary

Given an array of integers, count the number of subarrays that have exactly k odd numbers. This problem involves using prefix sums to efficiently calculate the number of odd numbers in a subarray.

Detailed Explanation

To solve this problem, we will use a two-pointer approach along with prefix sums. Let's consider a simple example: suppose we want to find all subarrays that have exactly 2 odd numbers. We can start by calculating the total count of odd numbers in the array using a prefix sum array. Then, we iterate over the array and maintain two pointers, start and end, which represent the current subarray. For each position in the array, we calculate the number of odd numbers in the subarray [start, end] by subtracting the previous prefix sum from the current prefix sum. If this count equals k, we increment our result.

Here's a step-by-step breakdown:

  1. Calculate the total count of odd numbers in the array using a prefix sum array.
  2. Initialize two pointers, start and end, to 0.
  3. Iterate over the array:
    • For each position, calculate the number of odd numbers in the subarray [start, end] by subtracting the previous prefix sum from the current prefix sum.
    • If this count equals k, increment our result.
    • Update start and end accordingly to consider the next subarray.
  4. Return the total count of subarrays with exactly k odd numbers.

Time complexity: O(n), where n is the length of the array. Space complexity: O(1), as we only need a constant amount of space for the prefix sum array and pointers.

Optimized Solutions

Java

View on GeeksforGeeks
public int countSubarrays(int[] arr, int k) {
    int n = arr.length;
    boolean[] odd = new boolean[n];
    for (int i = 0; i < n; i++) {
        if (arr[i] % 2 != 0) {
            odd[i] = true;
        }
    }
    int count = 0;
    int start = 0, end = 0;
    int oddCount = 0;
    while (end < n) {
        if (!odd[end]) {
            if (oddCount == k) {
                count++;
            }
            oddCount--;
        } else {
            oddCount++;
        }
        end++;
    }
    return count;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.