Largest 3-Same-Digit Number in String

easy string sliding window substring

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.

Inputnum = "6777133339"
Output"777"
Two good triples appear: "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;
}
Time: O(n) Space: O(1)