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:

  1. Initialize left and right pointers to 0.
  2. Initialize variables count and result to 0.
  3. Create a hashmap freq to store the frequency of remainders of elements when divided by p.
  4. 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 exceeds k, move the left pointer to the right until the size is less than or equal to k. Update the count accordingly while moving the left pointer.
    • Update the result by adding the difference of the current count and the count when the left pointer was moved.
  5. 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...