Skip to main content

Command Palette

Search for a command to run...

Count Largest Group

Published
2 min read
Count Largest Group
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

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.

LeetCode Problem - 1399

class Solution {
    public int countLargestGroup(int n) {

        // Create a map to store the sum of digits and their frequency
        Map<Integer, Integer> map = new HashMap<>();
        // Iterate through numbers from 1 to n
        for (int i = 1; i <= n; i++) {
            // Calculate the digit sum and update the map with the frequency
            map.put(digitSum(i), map.getOrDefault(digitSum(i), 0) + 1);
        }

        int answer = Integer.MIN_VALUE; // Initialize a variable to store the maximum frequency
        // Find the maximum frequency of digit sums in the map
        for (int e : map.values()) {
            if (e > answer) {
                answer = e;
            }
        }

        int count = 0; // Initialize a counter to count the groups with the maximum frequency
        // Count the number of groups that have the maximum frequency
        for (int e : map.values()) {
            if (e == answer) {
                count++;
            }
        }

        return count; // Return the count of the largest groups
    }

    // Helper method to calculate the sum of digits of a number
    public int digitSum(int digit) {
        String strDigit = String.valueOf(digit); // Convert the digit to a string
        int answer = 0; // Initialize a variable to store the sum of digits
        // Iterate through each character in the string
        for (char c : strDigit.toCharArray()) {
            answer += Integer.parseInt(String.valueOf(c)); // Add the numeric value of each character to the sum
        }
        return answer; // Return the sum of digits
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.