Count Windows With Sum Divisible
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
[3,6,9]=18 and [6,9,12]=27 — both div by 3
[1,2]=3, [4,5]=9 — both divisible by 3
Empty array
[1,3]=4, [3,5]=8 — both divisible by 2
[2,4]=6 divisible by 6
Algorithm Flow

Solution Approach
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
