This is a very important sliding window + prefix counting problem

Problem Summary

In this problem, you are given:

Your task is to count:

In simple words, you need to find all continuous subarrays where the count of odd numbers is exactly equal to k. This is a very common problem in data structures and algorithms, especially in coding interviews and competitive programming.

Key Insight

A brute-force approach would check all possible subarrays, which takes O(n²) time. This is inefficient for large inputs.

To optimize this, we use a powerful technique:

This transforms the problem into a more efficient sliding window problem with O(n) time complexity.

Core Idea

The main idea is based on the formula:

exactly(k) = atMost(k) - atMost(k-1)

This means:

The result gives us subarrays having exactly k odd numbers.

Why this works?

This works because:

This is a very important trick used in sliding window problems involving counting with constraints.

Function Idea

To implement this, we create a helper function:

This function calculates the number of subarrays that contain at most k odd numbers using the sliding window technique.

Sliding Window Logic

We use a sliding window approach where we maintain:

Steps involved:

This ensures we count all valid subarrays ending at the current index.

Java Solution

class Solution {

    // helper function: at most k odds
    private int atMost(int[] arr, int k) {

        int left = 0;
        int countOdd = 0;
        int result = 0;

        for (int right = 0; right < arr.length; right++) {

            if (arr[right] % 2 == 1) {
                countOdd++;
            }

            while (countOdd > k) {
                if (arr[left] % 2 == 1) {
                    countOdd--;
                }
                left++;
            }

            result += (right - left + 1);
        }

        return result;
    }

    public int countSubarrays(int[] arr, int k) {

        return atMost(arr, k) - atMost(arr, k - 1);
    }
}

Example Walkthrough

Input:

arr = [2, 5, 6, 9], k = 2

Now we find subarrays that contain exactly 2 odd numbers.

Valid subarrays are:

Output:

2

This example shows how the sliding window efficiently identifies valid subarrays without checking all possibilities.

Complexity

Key Takeaways

Pattern Recognition

If you see problems like:

You should think of:

Summary

This problem demonstrates an optimized approach to count subarrays with exactly k odd numbers using the sliding window technique and prefix counting logic. Instead of checking all subarrays, we transform the problem using the atMost(k) - atMost(k-1) formula, which allows us to solve it efficiently in linear time. This technique is widely used in real-world applications and coding interviews where performance optimization is critical.