algoadvance

Leetcode 1399. Count Largest Group

Problem Statement

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.

Clarifying Questions

  1. What is the range of n?
    • The value of n can range from 1 to 10,000.
  2. Are there any constraints on the input?
    • Yes, 1 <= n <= 10,000.
  3. What should the output be if n is a very small value (e.g., n = 1)?
    • For 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.

Strategy

  1. Calculate the digit sum for each number from 1 to n. Group the numbers by this digit sum.
  2. Use a hash map (or unordered_map in C++) to keep track of the size of each group.
  3. Determine the maximum size of these groups.
  4. Count how many groups have this maximum size.

Code

#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;
}

Time Complexity

This solution is efficient given the constraints and provides a quick way to determine the required count of groups with the largest sizes.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI