[LeetCode] K Divisible Elements Subarrays

2261. K Divisible Elements Subarrays

Given an integer array nums and two integers k and p, return the number of distinct subarrays which have at most k elements divisible by p.

Two arrays nums1 and nums2 are said to be distinct if:

  • They are of different lengths, or
  • There exists at least one index i where nums1[i] != nums2[i].

A subarray is defined as a non-empty contiguous sequence of elements in an array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int countDistinct(vector<int>& nums, int k, int p) {
unordered_set<string> vis;
int n = nums.size(), res = 0;
for(int i = 0; i < n; i++) {
int j = i;
string key = "";
for(int c = 0; c <= k and j < n; j++) {
if(nums[j] % p == 0) c++;
if(c <= k) {
key += to_string(nums[j]) + "#";
if(vis.insert(key).second)
res++;
}
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/k-divisible-elements-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.