Largest 3-Same-Digit Number in String

Updated on 05 June, 2025
Largest 3-Same-Digit Number in String header image

Problem Statement

In this task, you're presented with a string num that represents a large integer. You need to determine if there exists any "good" integer within this string. An integer qualifies as "good" if it meets both of the following criteria:

  • The integer is a substring of the string num and has exactly three characters.
  • All characters within this substring are the same, meaning it has only one unique digit.

Your goal is to identify the largest "good" integer and return it as a string. In cases where no such integer exists, you should return an empty string "". Please note that the substrings can include leading zeroes.

Examples

Example 1

Input:

num = "6777133339"

Output:

"777"

Explanation:

There are two distinct good integers: "777" and "333".  
"777" is the largest, so we return "777".

Example 2

Input:

num = "2300019"

Output:

"000"

Explanation:

"000" is the only good integer.

Example 3

Input:

num = "42352338"

Output:

""

Explanation:

No substring of length 3 consists of only one unique digit. Therefore, there are no good integers.

Constraints

  • 3 <= num.length <= 1000
  • num only consists of digits.

Approach and Intuition

From the examples and constraints provided, the solution requires checking every possible substring of length 3 within num to see if all characters are identical. Here’s a clear breakdown of the methodical approach:

  1. Initialize an empty string max_good to store the result.

  2. Loop through the string num from the start to length-2 (inclusive) to ensure each iteration gives us a valid substring of length 3:

    • For each index i, extract the substring from i to i+3.
    • Check if all characters in this substring are the same.
    • If they are the same and this substring is numerically greater than the current max_good, update max_good.
  3. After the loop, return max_good if it's not empty. Otherwise, return an empty string "".

This approach leverages string slicing and comparisons to efficiently find the desired substring. Given the constraint (num.length up to 1000), this method is computationally reasonable as it operates in linear time relative to the size of the input string.

Solutions

  • C++
  • Java
  • JavaScript
  • Python
cpp
class Solution {
public:
    string largestTriple(string digits) {
        // Initial value to compare with
        char highest = '\0';

        // Loop through the digits with a window of size 3
        for (int i = 0; i <= digits.length() - 3; ++i) {
            // Compare and check for three identical consecutive digits
            if (digits[i] == digits[i + 1] && digits[i] == digits[i + 2]) {
                // Update highest if necessary
                highest = max(highest, digits[i]);
            }
        }

        // Return result, based on whether we found any triple or not
        return highest == '\0' ? "" : string(3, highest);
    }
};

This summary provides an outline for a solution that finds the largest number composed of three identical consecutive digits within a given string. The solution, implemented in C++, involves iterating through the string with a sliding window of size three, identifying segments where all three characters are the same. Here's a concise breakdown of the approach:

  • Initialize a variable highest to store the maximum three-digit number found, starting its comparison with a null character.
  • Use a loop to traverse through the string with conditions strict enough to ensure all characters within the window are identical.
  • Use the C++ max function to update highest whenever a higher triplet is found.
  • Finally, return the result, which depends on whether any suitable triplet was found. If no triplet exists (i.e., highest remains unchanged as the null character), return an empty string. If a valid triplet was found, construct and return the string composed of three instances of the highest character.

This efficient approach ensures that you only need to traverse the string once, making it optimal for strings of small to moderate size where deep computational operations are not feasible. The solution leverages basic string and character manipulation to achieve its goal.

java
class Solution {
    public String findLargestTriple(String digits) {
        char highestTriple = '\0';

        for (int i = 0; i <= digits.length() - 3; ++i) {
            if (digits.charAt(i) == digits.charAt(i + 1) && digits.charAt(i) == digits.charAt(i + 2)) {
                highestTriple = (char) Math.max(highestTriple, digits.charAt(i));
            }
        }

        return highestTriple == '\0' ? "" : new String(new char[]{highestTriple, highestTriple, highestTriple});
    }
}

The code provided is a Java solution designed to find the largest number consisting of three identical digits (a "triple") within a given string of digits. Here's a breakdown of the functioning of this code:

  • Initialization: A variable highestTriple is initialized with a default null character '\0'. This variable will store the highest triple encountered during the string traversal.

  • String Traversal: The code iterates through the string using a loop, starting from the 0th index up to length - 3. This ensures that the code always has enough space to check groups of three characters.

  • Triple Checking: In each iteration, the code checks if the current digit and the next two digits are the same. If they are, it compares the digit with highestTriple using Math.max(). This helps update highestTriple with the greatest digit that forms a triple.

  • Result Computation: After completing the loop, the code checks if highestTriple is still the null character. If it is, it means no triple was found, and thus it returns an empty string. If a valid triple was found, the code returns a string made of three characters, all set to highestTriple.

By the end of this code execution, you obtain the largest number made of three identical digits in the input string, or an empty string if no such number exists. This compact and efficient approach ensures that the solution runs in linear time relative to the size of the input.

js
var findMaxTripleDigit = function(str) {
    let highestTriple = '\0';  // Initialize to the lowest character in ASCII

    for (let i = 0; i <= str.length - 3; ++i) {
        if (str[i] === str[i + 1] && str[i] === str[i + 2]) {
            highestTriple = String.fromCharCode(Math.max(highestTriple.charCodeAt(0), str.charCodeAt(i)));
        }
    }

    return highestTriple === '\0' ? '' : highestTriple.repeat(3);
};

This solution summary discusses a JavaScript function named findMaxTripleDigit that scans a string to find the largest triple-digit number composed of identical digits.

The function initializes highestTriple to the null character, representing the lowest ASCII value to start comparatives. It then iterates over the string, ensuring to check sequences with at least three characters remaining.

For each position, it checks if the current character and the next two characters are identical. If they are, it updates highestTriple by comparing and assigning the maximum ASCII value between the current highestTriple and the character at the current string position.

After the loop concludes, the function assesses if highestTriple remains the null character, indicating no triple identical digits were found. If unchanged, it returns an empty string. Otherwise, it returns highestTriple repeated three times, forming the largest triple-digit string found.

  • Use this function to efficiently identify the largest sequence of three identical digits in any given string.
  • Perfect for analyzing sequences in data strings where patterns determine significant values or actions.
python
class Solution:
    def findLargestGoodInteger(self, digits: str) -> str:
        largest_triplet = '\0'
        for i in range(len(digits) - 2):
            if digits[i] == digits[i + 1] == digits[i + 2]:
                largest_triplet = max(largest_triplet, digits[i])
        return '' if largest_triplet == '\0' else largest_triplet * 3

You need to identify the largest triplet of identical digits within a string using Python 3. The provided method findLargestGoodInteger accomplishes this by iterating through each character in the input string, checking for three consecutive identical characters. If such a sequence is found, it compares the sequence with the previously stored largest triplet and updates accordingly. If no triplet is found, the function returns an empty string; otherwise, it returns the largest triplet found. This method effectively finds and returns the largest repeating numeric triplet in a string format.

Comments

No comments yet.