Code Logo

Count Decreasing 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 decreasing. A window is strictly decreasing if each element is less than the previous element.

Check the first k elements. Then slide the window one position at a time. When an element leaves and a new element enters, only the pair involving the entering element needs to be checked. Track the count of violated pairs within the current window. When the violation count is zero, the window is valid (strictly decreasing).

Time is O(n) with O(1) space. This is the complement of the increasing windows problem; the comparison operator is simply inverted from < to >.

Example Input & Output

Example 1
Input
[1],1
Output
1
Explanation

Single element trivially decreasing

Example 2
Input
[],2
Output
0
Explanation

Empty array

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

Only [5,3,1] is decreasing

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

All increasing, none decreasing

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

[5,4,3],[4,3,2],[3,2,1] all decreasing

Algorithm Flow

Recommendation Algorithm Flow for Count Decreasing Windows
Recommendation Algorithm Flow for Count Decreasing 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;
    }
}