Count Windows With All Evens
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
No evens.
Single even.
[2,4,6] and [4,6,8] all even.
Only [2,4] is both even.
Algorithm Flow
Solution Approach
Use a sliding window to maintain the count of even numbers incrementally.
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
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 resComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
