We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Largest 3-Same-Digit Number in String

Number: 2346

Difficulty: Easy

Paid? No

Companies: opentext, PayPay


Problem Description

Given a numeric string, find the largest substring of length 3 in which all characters are the same. If no such substring exists, return an empty string.


Key Insights

  • Loop through the string and check every substring of length 3.
  • Validate if all three characters are identical.
  • Keep track of the maximum valid substring based on lexicographical (and numerical) order.
  • Since the digits range from 0-9, lexicographic comparison suffices.

Space and Time Complexity

Time Complexity: O(n), where n is the length of the input string. Space Complexity: O(1).


Solution

Iterate over the string by examining every contiguous substring of length 3. For each substring, check if all characters are the same by comparing the first character with the second and third. If valid, compare this substring with the currently stored maximum; update if it's larger. Return the maximum valid substring after processing the entire string.


Code Solutions

def largestGoodInteger(num: str) -> str:
    # Initialize the maximum valid substring
    max_good = ""
    # Iterate through the string stopping at len(num) - 2 since we check substrings of length 3
    for i in range(len(num) - 2):
        # Extract a substring of length 3
        substring = num[i:i+3]
        # Check if all three characters are the same
        if substring[0] == substring[1] == substring[2]:
            # Update max_good if this substring is greater than the current max_good
            if substring > max_good:
                max_good = substring
    # Return the result; empty string if no valid substring found
    return max_good

# Example usage:
print(largestGoodInteger("6777133339"))  # Output: "777"
← Back to All Questions