Largest 3-Same-Digit Number in String
Easy · Arrays & Hashing · Explanation and code example
Iteration (Optimal)
How it works
We can optimize further by observing that we only need to track the digit itself, not the entire 3-character substring. Since all good integers are formed by repeating a single digit three times, we just need to find the largest digit that appears three times consecutively. At the end, we can construct the result by repeating that digit three times.
Steps
- Initialize
resto-1to indicate no good integer found yet. - Iterate through the string, checking each window of size 3:
- If three consecutive characters are the same, extract the digit value and update
resif it is larger.
- If three consecutive characters are the same, extract the digit value and update
- If
resis still-1, return an empty string. Otherwise, return the digit repeated three times.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Forgetting That "000" Is a Valid Good Integer
The problem asks for the largest good integer, but "000" is still a valid answer if it is the only one found. Initializing the result to an empty string and checking only for non-zero matches causes "000" to be incorrectly skipped. Handle "000" explicitly or use comparison logic that includes it.
Returning the Wrong Result When No Good Integer Exists
If no three consecutive identical digits exist in the string, the answer should be an empty string. Returning "0", a default numeric value, or the last partial match leads to wrong answers. Always track whether any valid match was found before returning.
Python code example
class Solution:
def largestGoodInteger(self, num: str) -> str:
res = -1
for i in range(len(num) - 2):
if num[i] == num[i + 1] == num[i + 2]:
res = max(res, int(num[i]))
return str(res) * 3 if res != -1 else ""
C++ code example
class Solution {
public:
string largestGoodInteger(string num) {
int res = -1;
for (int i = 0; i < num.length() - 2; i++) {
if (num[i] == num[i + 1] && num[i] == num[i + 2]) {
res = max(res, num[i] - '0');
}
}
return res != -1 ? string(3, res + '0') : "";
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.