Code Logo

Count Windows With All Evens

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array and window size k, count windows where all elements are even numbers (divisible by 2).

Track the number of odd elements in the current window using a sliding counter. When the counter is 0, all elements are even, so increment the result.

O(n) time, O(1) space.

Example Input & Output

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

No evens.

Example 3
Input
[2],1
Output
1
Explanation

Single even.

Example 4
Input
[2,4,6,8],3
Output
2
Explanation

[2,4,6] and [4,6,8] all even.

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

Only [2,4] is both even.

Algorithm Flow

Recommendation Algorithm Flow for Count Windows With All Evens
Recommendation Algorithm Flow for Count Windows With All Evens

Solution Approach

Count odds in first window. Slide: adjust counter as elements leave/enter. When odd count is 0, all are even.

Best Answers

python
def solution(nums, k):
    if len(nums)<k: return 0
    odd=sum(1 for i in range(k) if nums[i]%2)
    res=1 if odd==0 else 0
    for i in range(k,len(nums)):
        if nums[i-k]%2: odd-=1
        if nums[i]%2: odd+=1
        if odd==0: res+=1
    return res