Skip to main content
Back to problems
#1796
Easy Algorithms

Second largest digit in a string

Hash Table String
53.8% acceptance
Feb 25, 2026
592
133
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn second_highest(s: String) -> i32 {
    let mut seen = [false; 10];
    for c in s.chars() {
      if c.is_ascii_digit() {
        seen[(c as u8 - b'0') as usize] = true;
      }
    }
    let mut count = 0;
    for d in (0..10).rev() {
      if seen[d] {
        count += 1;
        if count == 2 {
          return d as i32;
        }
      }
    }
    -1
  }
}