Code Logo

Count Windows With All Evens

Published at24 Jul 2026
Easy 0 views
Like0

Given an array of integers and a window size k, count how many subarrays of length k have an even number of even elements. Return the count of such windows.

For example, in [2, 1, 3, 4, 6] with k=3, the windows are: [2,1,3] has 1 even (2), [1,3,4] has 1 even (4), [3,4,6] has 2 evens (4,6). Only the last window qualifies, so return 1.

This problem teaches sliding window counting with condition evaluation. Instead of recomputing the entire window each time, you can slide the window and update the count of even numbers incrementally.

The solution initializes a window by counting evens in the first k elements, then slides the window: subtract the element leaving the window and add the element entering the window.

Edge cases include k larger than the array (return 0), an empty array (return 0), and k=1 (each single-element window's parity depends on that element).

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

Solution Approach

Use a sliding window to maintain the count of even numbers incrementally.

function countEvenWindows(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  count = 0, evenCount = 0
  for i = 0 to k - 1
    if arr[i] % 2 == 0 then evenCount = evenCount + 1
  if evenCount % 2 == 0 then count = count + 1
  for i = k to length(arr) - 1
    if arr[i - k] % 2 == 0 then evenCount = evenCount - 1
    if arr[i] % 2 == 0 then evenCount = evenCount + 1
    if evenCount % 2 == 0 then count = count + 1
  return count

Check edge cases. Count evens in the first window. Slide: when the element leaving the window is even, decrement the counter; when the element entering is even, increment it. After each slide, check if the current even count is even.

Time complexity is O(n), space complexity is O(1).

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