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.
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
- Time: O(n log n)
- Space: O(1)
