Code Logo

Count Windows With Sum Divisible

Published at25 Jul 2026
Easy 0 views
Like0

Given an integer array nums, a window size k, and a divisor d, count how many contiguous subarrays of length k have a sum divisible by d. Use the sliding window technique to maintain the running sum efficiently.

Compute the sum of the first k elements. Check if it is divisible by d (sum % d == 0). Then slide the window: subtract the leaving element and add the entering element. After each slide, check the new sum for divisibility. The modulo operation (%) checks divisibility.

Time is O(n) with O(1) space. The sliding window avoids recalculating the sum from scratch for each window.

Example Input & Output

Example 1
Input
[3,6,9,12],3,3
Output
2
Explanation

[3,6,9]=18 and [6,9,12]=27 — both div by 3

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

[1,2]=3, [4,5]=9 — both divisible by 3

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

Empty array

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

[1,3]=4, [3,5]=8 — both divisible by 2

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

[2,4]=6 divisible by 6

Algorithm Flow

Recommendation Algorithm Flow for Count Windows With Sum Divisible
Recommendation Algorithm Flow for Count Windows With Sum Divisible

Solution Approach

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

Best Answers

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