Count Largest Group Problem
Description
LeetCode Problem 1399.
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.
Example 1:
Input: n = 13
Output: 4
Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].
There are 4 groups with largest size.
Example 2:
Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.
Constraints:
1 <= n <= 10^4
Solution
Approach: Count Group Sizes by Digit Sum
Every number from 1 to n belongs to the group of its digit sum. Since n <= 10^4, a digit sum is at most 9 + 9 + 9 + 9 = 36, so an array of 37 counters holds every group size.
Go through the numbers in order, compute each digit sum with repeated % 10 and / 10, and increase that group's size. Keep track of the largest size so far and how many groups have it, updating both on the fly:
- If the group's new size is greater than the largest so far, it becomes the new record and is the only group with it:
ans = 1. - If it equals the largest, one more group shares the record:
ans += 1.
A group that grows past the record is counted correctly: when it ties the old record it is counted once, and on its next increase it sets a new record and ans restarts at 1. (Alternatively, fill all the sizes first and count the maximum afterwards.)
Complexity: O(n log n) time, since each number has O(log n) digits, and O(1) space for the 37 counters.
class Solution:
def countLargestGroup(self, n: int) -> int:
size = [0] * 37 # n <= 10^4, so a digit sum is at most 9 * 4 = 36
largest = ans = 0
for i in range(1, n + 1):
s, x = 0, i
while x:
s += x % 10
x //= 10
size[s] += 1
if size[s] > largest: # a new record: this is the only largest group so far
largest, ans = size[s], 1
elif size[s] == largest:
ans += 1
return ans