Count Largest Group - Problem

You are given an integer n.

We need to group the numbers from 1 to n according to the sum of their digits. For example, the numbers 14 and 5 belong to the same group (digit sum = 5), whereas 13 and 3 belong to different groups (digit sums 4 and 3).

Return the number of groups that have the largest size, i.e. the maximum number of elements.

Input & Output

Example 1 — Basic Case
$ Input: n = 13
Output: 4
💡 Note: Numbers 1-13 grouped by digit sum: {1:[1,10], 2:[2,11], 3:[3,12], 4:[4,13], 5:[5], 6:[6], 7:[7], 8:[8], 9:[9]}. Groups with digit sum 1,2,3,4 each have 2 elements (maximum). Four groups have this maximum size of 2.
Example 2 — Small Input
$ Input: n = 2
Output: 2
💡 Note: Numbers: {1:[1], 2:[2]}. Each group has size 1, which is the maximum. Two groups have this maximum size.
Example 3 — Larger Input
$ Input: n = 15
Output: 6
💡 Note: Groups: {1:[1,10], 2:[2,11], 3:[3,12], 4:[4,13], 5:[5,14], 6:[6,15], 7:[7], 8:[8], 9:[9]}. Maximum group size is 2, and 6 groups have this size.

Constraints

  • 1 ≤ n ≤ 104

Visualization

Tap to expand
Count Largest Group INPUT Numbers from 1 to n = 13 1 2 3 4 5 6 7 8 9 10 11 12 13 Digit Sum Examples: 14 --> 1+4 = 5 5 --> 5 13 --> 1+3 = 4 3 --> 3 Input Value n = 13 ALGORITHM STEPS 1 Create Hash Map Key: digit sum, Value: count 2 Iterate 1 to n Calculate digit sum for each 3 Update Hash Map Increment count for sum 4 Find Max Groups Count groups with max size Hash Map Result: Sum Numbers Cnt 1 1,10 2 2 2,11 2 3 3,12 2 4 4,13 2 5-9 5,6,7,8,9 1 each FINAL RESULT Group Size Analysis: Sum=1: [1,10] size=2 Sum=2: [2,11] size=2 Sum=3: [3,12] size=2 Sum=4: [4,13] size=2 Sum=5: [5] size=1 Sum=6: [6] size=1 Sum=7: [7] size=1 Sum=8: [8] size=1 Sum=9: [9] size=1 Maximum Size = 2 (4 groups) Output 4 Key Insight: Use a hash map to group numbers by their digit sum. The key is the digit sum, value is the count. Find the maximum group size first, then count how many groups have that size. Time: O(n * log(max)), Space: O(n) TutorialsPoint - Count Largest Group | Hash Map Approach
Asked in
Google 15 Amazon 12 Microsoft 8
28.4K Views
Medium Frequency
~12 min Avg. Time
423 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen