Code Logo

Count Decreasing Windows

Published at25 Jul 2026
Easy 1 views
Like0

Given an array of integers and a window size k, count how many subarrays of length k are strictly decreasing (each element is less than the previous one). Return the count of such windows.

For example, in [5, 4, 3, 2, 1] with k=3, all windows are decreasing: [5,4,3], [4,3,2], [3,2,1] — return 3. In [5, 4, 6, 3] with k=3, [5,4,6] is not decreasing (6>4), [4,6,3] is not decreasing — return 0.

This problem teaches sliding window with monotonic condition checking. Instead of checking each window from scratch, you can track whether the current window is decreasing incrementally.

The solution tracks the number of decreasing adjacent pairs within the current window. A window of size k is strictly decreasing if it has exactly k-1 decreasing pairs (each adjacent pair is decreasing).

Edge cases include k larger than the array (return 0), k=1 (single-element windows are trivially decreasing), and equal adjacent elements (they are not strictly decreasing).

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

Solution Approach

Track decreasing adjacent pairs within the sliding window.

function countDecreasing(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  count = 0, decPairs = 0
  for i = 1 to k - 1
    if arr[i] < arr[i-1] then decPairs = decPairs + 1
  if decPairs == k - 1 then count = count + 1
  for i = k to length(arr) - 1
    if arr[i-k+1] < arr[i-k] then decPairs = decPairs - 1
    if arr[i] < arr[i-1] then decPairs = decPairs + 1
    if decPairs == k - 1 then count = count + 1
  return count

Count decreasing pairs in the first window. Slide: when the pair leaving the window was decreasing, decrement; when the new pair entering is decreasing, increment. A window is valid when decPairs equals k-1.

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

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