Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created April 23, 2025 19:07
Show Gist options
  • Save Ifihan/12d28239d3821e75fb679bb1d155dd4c to your computer and use it in GitHub Desktop.
Save Ifihan/12d28239d3821e75fb679bb1d155dd4c to your computer and use it in GitHub Desktop.
Count Largest Group

Question

Approach

I grouped each number from 1 to n based on the sum of its digits. I used a dictionary to keep track of how many numbers belonged to each digit-sum group. For each number in the range, I calculated the digit sum by converting the number to a string, summing the integer values of its characters, and incremented the count in the corresponding group.

After processing all numbers, I looked at the values in the dictionary to determine the size of the largest group — this was just the maximum frequency among all groups. Then, I counted how many groups had this maximum size. That gave me the number of groups with the largest size, which I returned as the final answer.

Implementation

class Solution:
    def countLargestGroup(self, n: int) -> int:
        digit_sum_count = defaultdict(int)

        for num in range(1, n + 1):
            digit_sum = sum(int(d) for d in str(num))
            digit_sum_count[digit_sum] += 1

        max_size = max(digit_sum_count.values())
        largest_groups = sum(1 for count in digit_sum_count.values() if count == max_size)

        return largest_groups

Complexities

  • Time: O(n log n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment