#1399
Easy Algorithms Count largest group
Hash Table Math Counting
74.7% acceptance
Feb 25, 2026
802
1190
You are given an integer n.
We need to group the numbers from 1 to n according to the sum of its digits. For example, the numbers 14 and 5 belong to the same group, whereas 13 and 3 belong to different groups.
Return the number of groups that have the largest size, i.e. the maximum number of elements.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn count_largest_group(n: i32) -> i32 {
let mut groups = std::collections::HashMap::new();
for i in 1..=n {
let mut x = i;
let mut s = 0;
while x > 0 { s += x % 10; x /= 10; }
*groups.entry(s).or_insert(0) += 1;
}
let max_size = *groups.values().max().unwrap();
groups.values().filter(|&&v| v == max_size).count() as i32
}
}