Code Logo

Count Windows With All Positives

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 a majority of positive elements (more than half the elements are greater than 0). Return the count of such windows.

For example, in [1, -2, 3, 4, -1] with k=3, windows: [1,-2,3] has 2 positives (majority), [-2,3,4] has 2 positives (majority), [3,4,-1] has 2 positives (majority). Return 3. With k=2, [1,-2] has 1 positive (not majority), [-2,3] has 1, [3,4] has 2, [-1] is invalid. Return 1.

This problem teaches majority threshold checking within sliding windows. A majority requires more than k/2 elements satisfying the condition. The sliding window maintains a count of positives incrementally.

The solution initializes a positive count in the first window. Slide: adjust the count when the outgoing or incoming element is positive. After each slide, check if the count exceeds k/2.

Edge cases include k larger than the array (return 0), an empty array (return 0), and k=1 (a single positive element has majority 1 > 0.5).

Example Input & Output

Example 1
Input
[5,6,7],2
Output
2
Explanation

[5,6] and [6,7] both all positive.

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

No positive elements.

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

Only [2,3] is all positive.

Example 4
Input
[],2
Output
0
Explanation

Empty array.

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

Windows [1,2,3] and [2,3,4] are all positive.

Algorithm Flow

Recommendation Algorithm Flow for Count Windows With All Positives
Recommendation Algorithm Flow for Count Windows With All Positives

Solution Approach

Use a sliding window to maintain the count of positive numbers incrementally and check majority.

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

Count positives in the first window. Slide: decrement when a positive leaves, increment when a positive enters. Check majority after each slide by comparing the positive count to k/2.

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

Best Answers

python
def solution(nums, k):
    if len(nums)<k: return 0
    neg=sum(1 for i in range(k) if nums[i]<=0)
    res=1 if neg==0 else 0
    for i in range(k,len(nums)):
        if nums[i-k]<=0: neg-=1
        if nums[i]<=0: neg+=1
        if neg==0: res+=1
    return res