LeetCode 2261: K Divisible Elements Subarrays
Problem Description
Explanation:
To solve this problem, we can use a sliding window approach. We iterate through the array while maintaining a window that contains at most k
elements divisible by p
. We keep track of the count of subarrays that satisfy the conditions.
Algorithm:
- Initialize
left
andright
pointers to 0. - Initialize variables
count
andresult
to 0. - Create a hashmap
freq
to store the frequency of remainders of elements when divided byp
. - Iterate through the array using the
right
pointer:- Update the frequency of the current element's remainder in the
freq
hashmap. - If the size of
freq
exceedsk
, move theleft
pointer to the right until the size is less than or equal tok
. Update thecount
accordingly while moving theleft
pointer. - Update the
result
by adding the difference of the current count and the count when theleft
pointer was moved.
- Update the frequency of the current element's remainder in the
- Return the
result
.
Time Complexity: O(n) where n is the length of the input array. Space Complexity: O(k) where k is a constant (<= 200).
:
Solutions
class Solution {
public int countSubarrays(int[] nums, int k, int p) {
int left = 0, right = 0, count = 0, result = 0;
Map<Integer, Integer> freq = new HashMap<>();
while (right < nums.length) {
int rem = nums[right] % p;
freq.put(rem, freq.getOrDefault(rem, 0) + 1);
while (freq.size() > k) {
int leftRem = nums[left] % p;
freq.put(leftRem, freq.get(leftRem) - 1);
if (freq.get(leftRem) == 0) {
freq.remove(leftRem);
}
left++;
count--;
}
count++;
result += count;
right++;
}
return result;
}
}
Loading editor...