Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1399. Count Largest Group - Leetcode Solution

Problem Description

Given an integer n, consider every number from 1 to n (inclusive). For each number, calculate the sum of its digits. Group the numbers according to their digit sum. Your task is to count how many groups have the largest size. In other words, after grouping all numbers by their digit sum, find the size of the largest group(s), and return how many groups have that size.

Constraints:

  • 1 <= n <= 10^4
  • Each number from 1 to n is used exactly once.
  • Digit sum groups are determined by adding up the digits of each number.

Thought Process

At first glance, the problem appears to require grouping numbers by their digit sums and then identifying the most populous groups. A brute-force approach would involve iterating through all numbers from 1 to n, computing the digit sum for each, and tallying the frequencies of each group.

The main challenge is efficiently grouping the numbers and then determining which group(s) are largest. Using a data structure that allows for quick updates and queries (like a hash map) is key. Once all groups are formed, we need to find the maximum group size and count how many groups have that size.

The problem does not require us to list the numbers in each group—only to count the groups with the largest size. This simplifies our data structures and approach.

Solution Approach

We can solve the problem efficiently by following these steps:

  1. Iterate through all numbers from 1 to n:
    • For each number, calculate the sum of its digits.
  2. Group numbers by digit sum:
    • Use a hash map (dictionary) where the key is the digit sum and the value is the count of numbers having that digit sum.
  3. Find the largest group size:
    • After populating the hash map, determine the maximum value (the largest group size).
  4. Count groups with the largest size:
    • Count how many times the maximum value appears among the group sizes in the hash map.

We use a hash map for constant-time lookups and updates as we process each number. Calculating the digit sum can be done in logarithmic time relative to the number's size, but for our constraints, this is efficient enough.

Example Walkthrough

Let's take n = 13 as an example. We'll process numbers from 1 to 13:

  • 1: digit sum = 1
  • 2: digit sum = 2
  • 3: digit sum = 3
  • 4: digit sum = 4
  • 5: digit sum = 5
  • 6: digit sum = 6
  • 7: digit sum = 7
  • 8: digit sum = 8
  • 9: digit sum = 9
  • 10: digit sum = 1
  • 11: digit sum = 2
  • 12: digit sum = 3
  • 13: digit sum = 4

Now, group sizes:

  • Digit sum 1: numbers {1, 10} → size 2
  • Digit sum 2: numbers {2, 11} → size 2
  • Digit sum 3: numbers {3, 12} → size 2
  • Digit sum 4: numbers {4, 13} → size 2
  • Digit sum 5: {5} → size 1
  • Digit sum 6: {6} → size 1
  • Digit sum 7: {7} → size 1
  • Digit sum 8: {8} → size 1
  • Digit sum 9: {9} → size 1
The largest group size is 2, and there are 4 groups of this size (digit sums 1, 2, 3, and 4).

Output: 4

Code Implementation

class Solution:
    def countLargestGroup(self, n: int) -> int:
        from collections import defaultdict
        groups = defaultdict(int)
        for num in range(1, n + 1):
            digit_sum = sum(int(d) for d in str(num))
            groups[digit_sum] += 1
        max_size = max(groups.values())
        return sum(1 for size in groups.values() if size == max_size)
      
class Solution {
public:
    int countLargestGroup(int n) {
        unordered_map<int, int> groups;
        for (int num = 1; num <= n; ++num) {
            int sum = 0, x = num;
            while (x) {
                sum += x % 10;
                x /= 10;
            }
            groups[sum]++;
        }
        int max_size = 0, count = 0;
        for (auto &p : groups) {
            if (p.second > max_size) {
                max_size = p.second;
                count = 1;
            } else if (p.second == max_size) {
                count++;
            }
        }
        return count;
    }
};
      
class Solution {
    public int countLargestGroup(int n) {
        Map<Integer, Integer> groups = new HashMap<>();
        for (int num = 1; num <= n; num++) {
            int sum = 0, x = num;
            while (x > 0) {
                sum += x % 10;
                x /= 10;
            }
            groups.put(sum, groups.getOrDefault(sum, 0) + 1);
        }
        int max = 0, count = 0;
        for (int size : groups.values()) {
            if (size > max) {
                max = size;
                count = 1;
            } else if (size == max) {
                count++;
            }
        }
        return count;
    }
}
      
var countLargestGroup = function(n) {
    const groups = {};
    for (let num = 1; num <= n; num++) {
        let sum = 0, x = num;
        while (x > 0) {
            sum += x % 10;
            x = Math.floor(x / 10);
        }
        groups[sum] = (groups[sum] || 0) + 1;
    }
    let max = 0, count = 0;
    for (let key in groups) {
        if (groups[key] > max) {
            max = groups[key];
            count = 1;
        } else if (groups[key] === max) {
            count++;
        }
    }
    return count;
};
      

Time and Space Complexity

Brute-force approach:

  • Iterate through all numbers from 1 to n and for each, group by digit sum. Each digit sum computation is O(log n) (since a number has up to log10n digits).
  • Total time: O(n log n)
  • Space: O(n) in the worst case (if all digit sums are unique), but in practice, much less since digit sums are bounded (max 36 for 4-digit numbers).
Optimized approach:
  • The above solution is already optimal for the constraints, as each number is processed exactly once and grouping is efficient.
  • Time: O(n log n)
  • Space: O(D), where D is the number of possible digit sums (at most 36 for n up to 10,000).

The use of a hash map or array for counting groups keeps both time and space within acceptable limits for the problem's constraints.

Summary

This problem demonstrates a classic grouping task, where we classify numbers by a computed property (digit sum), then analyze the resulting groups. By using a hash map to tally group sizes, we ensure efficient updates and queries. The solution is elegant in its simplicity: process each number, track group sizes, and count the largest ones. No advanced data structures are needed, and the approach scales well for the given constraints.