Largest 3-Same-Digit Number in String
Problem
You are given a string num of digits. A length-3 substring is good if all three of its characters are the same digit (e.g. "777"). Return the largest good substring as a string, or the empty string "" if no good substring exists. Leading zeroes are allowed, so "000" is a valid answer.
num = "6777133339""777""777" and "333". Since all good triples have length 3, comparing them as numbers is the same as comparing the strings; "777" is the largest.def largestGoodInteger(num):
best = "" # largest good triple so far
for i in range(len(num) - 2): # window start index
a, b, c = num[i], num[i+1], num[i+2]
if a == b == c: # all three digits equal?
cand = num[i:i+3] # the good triple
if cand > best: # same length, so > is numeric
best = cand
return best
function largestGoodInteger(num) {
let best = ""; // largest good triple so far
for (let i = 0; i <= num.length - 3; i++) {
const a = num[i], b = num[i + 1], c = num[i + 2];
if (a === b && b === c) { // all three digits equal?
const cand = num.slice(i, i + 3); // the good triple
if (cand > best) best = cand; // same length, so > is numeric
}
}
return best;
}
String largestGoodInteger(String num) {
String best = ""; // largest good triple so far
for (int i = 0; i + 2 < num.length(); i++) {
char a = num.charAt(i), b = num.charAt(i + 1), c = num.charAt(i + 2);
if (a == b && b == c) { // all three digits equal?
String cand = num.substring(i, i + 3);
if (cand.compareTo(best) > 0) best = cand;
}
}
return best;
}
string largestGoodInteger(string num) {
string best = ""; // largest good triple so far
for (int i = 0; i + 2 < (int)num.size(); i++) {
char a = num[i], b = num[i + 1], c = num[i + 2];
if (a == b && b == c) { // all three digits equal?
string cand = num.substr(i, 3);
if (cand > best) best = cand; // same length, so > is numeric
}
}
return best;
}
Explanation
A good integer is simply a length-3 window in which the same digit appears three times. We slide a width-3 window across num and test each window for this property.
At window start i we look at the three characters num[i], num[i+1], num[i+2]. If they are all equal, that window is a good triple and becomes a candidate answer.
Among candidates we keep the largest. Because every good triple has exactly three characters, comparing them as strings is identical to comparing them as numbers — "888" > "333" both lexicographically and numerically. The empty string "" is smaller than any real triple, so it is a safe initial value that also doubles as the "none found" answer.
A neat alternative, matching the official hint, is to test for the patterns "999", "888", …, "000" in that order and return the first one that occurs as a substring — the first match is automatically the maximum. The scan shown here is the most direct single-pass version.
Example: "6777133339" → the window at index 1 is "777" and the window at index 5 is "333". The larger is "777".