#3712
Easy Algorithms Sum of elements with frequency divisible by k
Array Hash Table Counting
77.6% acceptance
Feb 24, 2026
54
3
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.
Solution
Rust
Time O(n)
Space O(n)
impl Solution {
pub fn sum_divisible_by_k(nums: Vec<i32>, k: i32) -> i32 {
let mut freq = std::collections::HashMap::new();
for &x in &nums {
*freq.entry(x).or_insert(0) += 1;
}
freq.iter()
.filter(|&(_, cnt)| cnt % k == 0)
.map(|(&val, &cnt)| val * cnt)
.sum()
}
}