Second Largest Digit in a String

easy string scan

Problem

Given a string s that mixes lowercase letters and digits, return the second largest distinct digit that appears in it. If fewer than two different digits are present, return -1.

Inputs = "dfa12321adfafd"
Output2
The digits present are {1, 2, 3}. The largest is 3 and the second largest is 2.

def second_highest(s):
    first = -1
    second = -1
    for ch in s:
        if ch.isdigit():
            d = int(ch)
            if d > first:
                second = first
                first = d
            elif d < first and d > second:
                second = d
    return second
function secondHighest(s) {
  let first = -1;
  let second = -1;
  for (const ch of s) {
    if (ch >= '0' && ch <= '9') {
      const d = ch.charCodeAt(0) - 48;
      if (d > first) {
        second = first;
        first = d;
      } else if (d < first && d > second) {
        second = d;
      }
    }
  }
  return second;
}
class Solution {
    public int secondHighest(String s) {
        int first = -1;
        int second = -1;
        for (char ch : s.toCharArray()) {
            if (ch >= '0' && ch <= '9') {
                int d = ch - '0';
                if (d > first) {
                    second = first;
                    first = d;
                } else if (d < first && d > second) {
                    second = d;
                }
            }
        }
        return second;
    }
}
int secondHighest(string s) {
    int first = -1;
    int second = -1;
    for (char ch : s) {
        if (ch >= '0' && ch <= '9') {
            int d = ch - '0';
            if (d > first) {
                second = first;
                first = d;
            } else if (d < first && d > second) {
                second = d;
            }
        }
    }
    return second;
}
Time: O(n) Space: O(1)