Count Windows With All Odd Elements
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
[1,3] and [3,5] all odd.
Only [1,3,5] is all odd.
Algorithm Flow
Solution Approach
Count how many subarrays of size k consist entirely of odd numbers. Use a sliding window with a counter tracking odd numbers in the current window. When the odd count equals k, increment the result.
Only when every element in the window is odd does the odd count equal k. The sliding window updates in O(1) per position.
Time O(n), Space O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
