#1399
Count Largest Group
EasyHash TableMathCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Instead of recalculating the digit sum multiple times, we can directly count the occurrences of each digit sum in a single pass, making the process more efficient.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dictionary to count groups based on the sum of digits.
- 2Step 2: For each number from 1 to n, calculate the sum of its digits and update the count in the dictionary.
- 3Step 3: Find the maximum group size and count how many groups have that size.
solution.py9 lines
1def countLargestGroup(n):
2 groups = defaultdict(int)
3
4 for i in range(1, n + 1):
5 digit_sum = sum(int(d) for d in str(i))
6 groups[digit_sum] += 1
7
8 max_size = max(groups.values())
9 return sum(1 for size in groups.values() if size == max_size)ℹ
Complexity note: The time complexity is O(n) because we only pass through the numbers once, calculating the digit sum in constant time for each number. The space complexity is O(n) due to storing the counts of groups.
- 1The sum of digits can be calculated efficiently using string manipulation.
- 2Using a dictionary (or hash map) allows us to count occurrences without worrying about the size of the groups in advance.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.