Code Logo

Count Increasing Windows

Published at25 Jul 2026
Easy 0 views
Like0

Given an integer array nums and a window size k, count how many contiguous subarrays of length k are strictly increasing. A window is strictly increasing if each element is greater than the previous element.

Check the first k elements. Then slide the window one position at a time. When an element leaves the window and a new element enters, only the pair (nums[i-1], nums[i]) for the entering element needs to be checked to determine if the window remains strictly increasing. Track the count of violated pairs within the current window. When the violation count is zero, the window is valid.

Time is O(n) with O(1) space. Each element is compared with its predecessor at most twice: once when it enters the window and once when it leaves.

Example Input & Output

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

[1,3,5] and [2,4,6] are increasing

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

All decreasing, none increasing

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

[1,2],[2,3],[3,4] all increasing

Example 4
Input
[1],1
Output
1
Explanation

Single element trivially increasing

Example 5
Input
[],2
Output
0
Explanation

Empty array

Algorithm Flow

Recommendation Algorithm Flow for Count Increasing Windows
Recommendation Algorithm Flow for Count Increasing Windows

Solution Approach

function solution(nums, k) {
  if (nums.length < k) return 0;
  var violations = 0;
  for (var i = 1; i < k; i++) {
    if (nums[i] <= nums[i-1]) violations++;
  }
  var count = violations === 0 ? 1 : 0;
  for (var i = k; i < nums.length; i++) {
    if (nums[i-k] >= nums[i-k+1]) violations--;
    if (nums[i] <= nums[i-1]) violations++;
    if (violations === 0) count++;
  }
  return count;
}

Best Answers

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