Second Largest Digit in a String
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.
s = "dfa12321adfafd"2def 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;
}
Explanation
We want the second largest distinct digit. A clean way is to keep two running winners as we read the string left to right: first (the largest digit so far) and second (the largest digit that is strictly smaller than first). Both start at -1, which doubles as the "not found" answer.
For each character we first check whether it is a digit. Non-digit letters are simply skipped. When we hit a digit d there are two interesting cases:
If d is bigger than the current champion first, then the old champion gets demoted to second and d becomes the new first. If instead d is strictly between second and first (smaller than first but larger than second), it becomes the new runner-up. The strict d < first check is what keeps the two values distinct — a repeated copy of the largest digit never sneaks into second.
Example: s = "dfa12321adfafd". Letters are ignored. The first digit 1 makes first = 1. Then 2 beats it, so second = 1, first = 2. Then 3 beats that, so second = 2, first = 3. The remaining 2 and 1 are not larger than first and not larger than second, so nothing changes. The answer is second = 2.
If the string has at most one distinct digit (or none), second never moves off -1, which is exactly the value we return.