#2264

Largest 3-Same-Digit Number in String

Easy
StringHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking every substring, we can directly check for the largest possible good integers from '999' to '000'. This way, we can stop as soon as we find the first match, making the solution efficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Loop through digits from '9' to '0'.
  2. 2Step 2: For each digit, create a substring of three of that digit (e.g., '999', '888').
  3. 3Step 3: Check if this substring exists in the original string. If it does, return it immediately as it will be the largest.
  4. 4Step 4: If no good integer is found after the loop, return an empty string.
solution.py6 lines
1def largestGoodInteger(num):
2    for digit in range(9, -1, -1):
3        good_integer = str(digit) * 3
4        if good_integer in num:
5            return good_integer
6    return ""

Complexity note: The time complexity is O(n) because we only scan the string once for each of the 10 digits. The space complexity is O(1) since we are not using any additional space that grows with input size.

  • 1Checking for the largest good integer first allows for early termination.
  • 2Using a direct search for fixed patterns is more efficient than checking all substrings.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.