Python 1399.py
class Solution:
def countLargestGroup(self, n: int) -> int:
count = [ 0 ] * 40
# brute force
for i in range(1, n + 1):
digitsum = 0
ii = i
while ii > 0:
digitsum += ii % 10
ii //= 10
count[digitsum] += 1
high = max(count)
return sum(1 if c == high else 0 for c in count)
Difficulty
and has an acceptance rate of about 75% (200k+ submissions).
Typical patterns to solve this problem:
- Hash Table
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method countLargestGroup that determines how many digit-sum groups contain the maximum number of integers in the range 1 to n. The algorithm iterates through each integer, computes its digit sum, tallies occurrences in a fixed-size array, and finally extracts the count of groups that share the highest frequency.
Step 1: Initialize Counter Array
count = [0] * 40
A list of length 40 is allocated to store the frequency of each possible digit sum. The size 40 comfortably exceeds the maximum digit sum for any integer up to the typical problem constraints (for example, a 10-digit number has a digit sum ≤ 90, but the problem limits n such that 40 is sufficient). All entries start at zero, ready to be incremented.
Step 2: Compute Digit Sum for Each Number
for i in range(1, n + 1):
digitsum = 0
ii = i
while ii > 0:
digitsum += ii % 10
ii //= 10
count[digitsum] += 1
The loop iterates from 1 through n. For each integer i, a temporary variable ii preserves the original value while the inner while extracts each decimal digit using the modulus operator (% 10). The digit is added to digitsum, and ii is reduced by integer division (// 10). When ii becomes zero, the full digit sum is known and the corresponding slot in count is incremented.
Step 3: Track Maximum Frequency
high = max(count)
return sum(1 if c == high else 0 for c in count)
After all numbers have been processed, max(count) yields the highest occurrence count among all digit-sum groups. The final return statement iterates over count and adds one for each entry equal to high. The sum therefore represents the number of groups that share the maximum size.
Edge Cases Handled
When n equals 1, the loop runs once, the digit sum of 1 is computed, and count[1] becomes 1. The maximum frequency is 1, and the generator expression counts the single group, returning 1. If n is zero (though the problem definition typically excludes this), the for loop would not execute, leaving all entries at zero; max(count) would be zero and the sum would count every slot, resulting in 40. This behavior reflects a consistent handling of empty input ranges.
The algorithm also gracefully manages numbers with leading zeros in their decimal representation because the digit-sum calculation inherently ignores any non-existent leading zeros. Large values of n that produce digit sums beyond the allocated array size would cause an IndexError, but the chosen size of 40 is deliberately selected to avoid that scenario within the expected input domain.
Performance Optimizations
The code avoids dynamic data structures such as dictionaries or default dictionaries, opting instead for a pre-allocated list. This choice eliminates hash-based overhead and provides O(1) access for incrementing group counts. The digit-sum computation uses integer arithmetic exclusively, which is faster than converting numbers to strings and iterating over characters. By reusing the variable ii for the inner loop, the original loop variable i remains untouched, preventing unnecessary object creation. The final aggregation uses a generator expression inside sum, which iterates lazily and avoids constructing an intermediate list. These decisions collectively keep the runtime tight and memory usage predictable.
ELI5 - Simplified Explanation
Imagine you have a big box of numbered blocks starting from one all the way up to a special number. You want to sort these blocks into piles based on a secret rule. For each block, you look at the digits written on it and add them together to get a new smaller number. For example, if a block has the number twelve, you add one and two together to make three. You then put that block into the pile labeled three.
You keep doing this for every single block until they are all inside their matching piles. Some piles will grow quite tall while others might stay very small. After all the blocks are sorted, you look at all the piles to find out which ones grew the tallest because they have the most blocks. Finally, you count how many of those tallest piles exist to see how many groups are tied for the biggest size.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | |||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| varunu28 | Java | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fsq | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| lzl124631x | C++ | ||||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1184: Distance Between Bus Stops
- problem 1342: Number of Steps to Reduce a Number to Zero
- problem 1496: Path Crossing
- problem 1646: Get Maximum in Generated Array
- problem 1893: Check if All the Integers in a Range Are Covered
- problem 2404: Most Frequent Even Element
- problem 2432: The Employee That Worked on the Longest Task
- problem 2451: Odd String Difference
- problem 2540: Minimum Common Value
- problem 609: Find Duplicate File in System
- problem 1169: Invalid Transactions
- problem 1711: Count Good Meals
- problem 1781: Sum of Beauty of All Substrings
- problem 1865: Finding Pairs With a Certain Sum
- problem 1871: Jump Game VII
- problem 2013: Detect Squares
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality