Formatted question description: https://leetcode.ca/all/1796.html

# 1796. Second Largest Digit in a String

Easy

## Description

Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.

An alphanumeric string is a string consisting of lowercase English letters and digits.

Example 1:

Input: s = “dfa12321afd”

Output: 2

Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = “abc1111”

Output: -1

Explanation: The digits that appear in s are . There is no second largest digit.

Constraints:

• 1 <= s.length <= 500
• s consists of only lowercase English letters and/or digits.

## Solution

Loop over s and count the occurrences of all digits. Then loop over all digits backwards and find the second largest digit that has occurrence greater than 0. If such a digit exists, return the digit. Otherwise, return -1.

class Solution {
public int secondHighest(String s) {
int[] counts = new int;
int length = s.length();
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9')
counts[c - '0']++;
}
boolean flag = false;
for (int i = 9; i >= 0; i--) {
if (counts[i] > 0) {
if (!flag)
flag = true;
else
return i;
}
}
return -1;
}
}