1399. Count Largest Group LeetCode Solution
In this guide, you will get 1399. Count Largest Group LeetCode Solution with the best time and space complexity. The solution to Count Largest Group problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Count Largest Group solution in C++
- Count Largest Group solution in Java
- Count Largest Group solution in Python
- Additional Resources
Problem Statement of Count Largest Group
You are given an integer n.
Each number from 1 to n is grouped according to the sum of its digits.
Return the number of groups that have the largest size.
Example 1:
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:
[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].
There are 4 groups with largest size.
Example 2:
Input: n = 2
Output: 2
Explanation: There are 2 groups [1], [2] of size 1.
Constraints:
1 <= n <= 104
Complexity Analysis
- Time Complexity: O(n\log n)
- Space Complexity: O(n)
1399. Count Largest Group LeetCode Solution in C++
class Solution {
public:
int countLargestGroup(int n) {
vector<int> count(9 * 4 + 1);
for (int i = 1; i <= n; ++i)
++count[getDigitSum(i)];
return ranges::count(count, ranges::max(count));
}
private:
int getDigitSum(int num) {
int digitSum = 0;
while (num > 0) {
digitSum += num % 10;
num /= 10;
}
return digitSum;
}
};
/* code provided by PROGIEZ */
1399. Count Largest Group LeetCode Solution in Java
class Solution {
public int countLargestGroup(int n) {
int[] count = new int[9 * 4 + 1];
for (int i = 1; i <= n; ++i)
++count[getDigitSum(i)];
final int mx = Arrays.stream(count).max().getAsInt();
return (int) Arrays.stream(count).filter(c -> c == mx).count();
}
private int getDigitSum(int num) {
int digitSum = 0;
while (num > 0) {
digitSum += num % 10;
num /= 10;
}
return digitSum;
}
}
// code provided by PROGIEZ
1399. Count Largest Group LeetCode Solution in Python
class Solution:
def countLargestGroup(self, n: int) -> int:
count = [0] * (9 * 4 + 1)
for i in range(1, n + 1):
count[self._getDigitSum(i)] += 1
return count.count(max(count))
def _getDigitSum(self, num: int) -> int:
return sum(int(digit) for digit in str(num))
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.