Leetcode 1399. Count Largest Group
Given an integer n
. Each number from 1 to n is grouped according to the sum of its digits. Return how many groups have the largest size.
n
?
n
can range from 1 to 10,000.1 <= n <= 10,000
.n
is a very small value (e.g., n = 1
)?
n = 1
, the only group is {1}
with the sum of digits being 1, hence the number of groups with the largest size is 1.n
. Group the numbers by this digit sum.#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int sumOfDigits(int num) {
int sum = 0;
while (num) {
sum += num % 10;
num /= 10;
}
return sum;
}
int countLargestGroup(int n) {
unordered_map<int, int> groupSizes;
// Calculate the size of each group
for (int i = 1; i <= n; i++) {
int sum = sumOfDigits(i);
groupSizes[sum]++;
}
// Find the maximum size of groups
int maxSize = 0;
for (const auto &pair : groupSizes) {
maxSize = max(maxSize, pair.second);
}
// Count the groups that have this maximum size
int count = 0;
for (const auto &pair : groupSizes) {
if (pair.second == maxSize) {
count++;
}
}
return count;
}
int main() {
int n;
cout << "Enter n: ";
cin >> n;
cout << "Number of largest groups: " << countLargestGroup(n) << endl;
return 0;
}
i
, the time complexity is O(log(i))
(since there are roughly log(i)
digits). However, summing the digits for numbers from 1 to n
can be approximated by O(n log(n))
.O(1)
time.O(n)
keys, takes O(n)
.O(n log n)
.This solution is efficient given the constraints and provides a quick way to determine the required count of groups with the largest sizes.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?