Problem 1399

Abstract / Summary

Count how many digit groups have the most numbers that can be reached by repeatedly summing the digits of each number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
14 lines | 415 bytes | submitted December 12, 2023 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 75% (200k+ submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.19 | σ = 0.94

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
28 links | 16 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

17 solutions   December 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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