[LeetCode] Sum of Elements With Frequency Divisible by K

3712. Sum of Elements With Frequency Divisible by K

You are given an integer array nums and an integer k.

Return an integer denoting the sum of all elements in nums whose frequency is divisible by k, or 0 if there are no such elements.

Note: An element is included in the sum exactly as many times as it appears in the array if its total frequency is divisible by k.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int sumDivisibleByK(vector<int>& nums, int k) {
unordered_map<int,int>freq;
for(auto& n : nums) freq[n]++;
int res = 0;
for(auto& [x,v] : freq) if(v % k == 0) res += x * v;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/10/13/PS/LeetCode/sum-of-elements-with-frequency-divisible-by-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.