[Hacker Rank] Non-Divisible Subset

Non-Divisible Subset

  • Time : O(n + k)
  • Space : O(k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int nonDivisibleSubset(int k, vector<int> s) {
unordered_map<int, int> mp;
for(auto& n : s) {
mp[n % k]++;
}
int res = 0;
for(auto& [div, freq] : mp) {
if(div * 2 == k) res++;
else if(div == 0) res++;
else {
int o = k - div;
if(!mp.count(o)) res += freq;
else if(div > o) continue;
else if(div < o) res += max(freq, mp[o]);
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/06/PS/HackerRank/non-divisible-subset/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.