Code Logo

Count Windows With All Positive Elements

Published at24 Jul 2026
Easy 0 views
Like0

Given an integer array and window size k, count how many windows of length k contain only positive numbers (greater than 0). Instead of checking every element in each window, maintain a counter of non-positive elements in the current window.

Start by counting how many elements in the first k elements are non-positive (

<= 0). If this count is zero, the first window qualifies. Then slide through the array. When the leaving element is non-positive, decrement the counter. When the entering element is non-positive, increment it. After each slide, if the counter is zero, all elements in the current window are positive, so increment the result.

This counter-based approach is O(n) time and O(1) space because only two elements change per window slide, requiring at most 2 counter adjustments. Without this optimization, checking each window would require O(k) comparisons per window.

The same pattern applies to any binary condition: all even, all odd, all negative, all divisible by a number, etc. The counter tracks how many elements in the current window FAIL the condition, and when it reaches zero, all elements PASS.

This generalizes to any property that can be verified with a "failure counter." The same pattern works for checking if all elements are even, all are negative, all are zeros, etc.

Example Input & Output

Example 1
Input
[],2
Output
0
Example 2
Input
[1,-1,2],2
Output
0
Explanation

Neither [1,-1] nor [-1,2] is all positive

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

Windows: [1,2,3] and [2,3,4] all positive

Algorithm Flow

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

Solution Approach

Count non-positive elements in first window. Slide: update count. When count is 0, all are positive.

Best Answers

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