Code Logo

Count Windows With All Positive Elements

Published at24 Jul 2026
Easy 1 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

Solution Approach

Count how many subarrays of size k consist entirely of positive numbers using a sliding window. Track positive count in the current window. When the count equals k, all elements are positive and we increment the result.

function countAllPositiveWindows(arr, k) {
  var pos = 0, count = 0;
  for (var i = 0; i < k; i++) if (arr[i] > 0) pos++;
  if (pos === k) count++;
  for (var i = k; i < arr.length; i++) {
    if (arr[i - k] > 0) pos--;
    if (arr[i] > 0) pos++;
    if (pos === k) count++;
  }
  return count;
}

The condition pos === k means every element in the window is positive. Zero and negative values reduce the count.

Time O(n), Space O(1).

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;
    }
}