Count Largest Group — LeetCode 1399 Python Solution

EasyHash TableMath
Problem
#1399
Reading time
3 min

The problem

You are given an integer n. We need to group the numbers from 1 to n according to the sum of its digits.

Example

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:

Python solution

Python
class Solution:
    def countLargestGroup(self, n: int) -> int:
        cnt = Counter()
        ans = mx = 0
        for i in range(1, n + 1):
            s = 0
            while i:
                s += i % 10
                i //= 10
            cnt[s] += 1
            if mx < cnt[s]:
                mx = cnt[s]
                ans = 1
            elif mx == cnt[s]:
                ans += 1
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n), where n is the given number auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1399. Count Largest Group is filed here because LeetCode tags it Math, which is the vocabulary this hub collects.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1399. Count Largest Group?
LeetCode 1399. Count Largest Group is rated Easy on LeetCode.
What is the time complexity of LeetCode 1399. Count Largest Group?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1399. Count Largest Group?
The Python solution on this page uses O(\log n), where n is the given number auxiliary space.
What topics does LeetCode 1399. Count Largest Group cover?
LeetCode 1399. Count Largest Group is tagged Hash Table and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview