Code Logo

Count Windows With All Odd Elements

Published at24 Jul 2026
Easy 2 views
Like0

Given an integer array and window size k, count how many windows of length k contain only odd numbers using the sliding window technique.

Track the number of even elements in the current window. When this count is zero, all elements in the window are odd, so increment the result counter. Slide the window one position at a time, updating the even count as elements leave and enter.

This extends the sliding window pattern beyond binary properties. Instead of tracking a specific value, we track whether elements satisfy a condition (being even). The counter tracks non-conforming elements, and when it reaches zero, the window satisfies the condition.

The time complexity is O(n) with O(1) space. Edge cases include empty arrays (return 0), k larger than array length (return 0), and arrays with no odd numbers (return 0).

The even-count tracking generalizes to any binary condition on array elements. By maintaining a counter of elements that FAIL the condition, we determine when all elements PASS the condition (counter == 0). This pattern applies to constraints like all positive, all negative, all divisible by a number, etc. The even-count tracking generalizes to any binary condition on array elements. By maintaining a counter of elements that FAIL the condition, we determine when all elements PASS the condition (counter == 0). This pattern applies to constraints like all positive, all negative, all divisible by a number, etc. The counter approach is more efficient than checking every element in each window.

Example Input & Output

Example 1
Input
[1],1
Output
1
Example 2
Input
[],2
Output
0
Example 3
Input
[1,3,5],2
Output
2
Explanation

[1,3] and [3,5] all odd.

Example 4
Input
[2,4,6],2
Output
0
Example 5
Input
[1,3,5,2,4],3
Output
1
Explanation

Only [1,3,5] is all odd.

Algorithm Flow

Recommendation Algorithm Flow for Count Windows With All Odd Elements
Recommendation Algorithm Flow for Count Windows With All Odd Elements

Solution Approach

Count evens in first window. Slide: update even count. When even count is 0, increment result.

Best Answers

java
class Solution {
    public int solution(int[] nums, int k) {
        if (nums.length<k) return 0;
        int ev=0;for(int i=0;i<k;i++)if(nums[i]%2==0)ev++;
        int r=(ev==0?1:0);
        for(int i=k;i<nums.length;i++){if(nums[i-k]%2==0)ev--;if(nums[i]%2==0)ev++;if(ev==0)r++;}
        return r;
    }
}