Second Largest Digit in a String - Problem

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.

Input & Output

Example 1 — Basic Mixed String
$ Input: s = "dfa12321afd"
Output: 2
💡 Note: Digits present: 1, 2, 3. Largest is 3, second largest is 2.
Example 2 — Duplicate Digits
$ Input: s = "abc1111"
Output: -1
💡 Note: Only digit 1 appears, so there's no second largest digit.
Example 3 — No Digits
$ Input: s = "abcdef"
Output: -1
💡 Note: No digits in the string, return -1.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of lowercase English letters and digits.

Visualization

Tap to expand
Second Largest Digit in StringInput: "dfa12321afd"dfa12321afdExtract digits: 1, 2, 3, 2, 1Unique digits: {1, 2, 3}321Largest2nd LargestSmallestOutput: 2
Understanding the Visualization
1
Input
Alphanumeric string with digits and letters mixed
2
Extract
Identify all digit characters (0-9)
3
Find
Return second largest unique digit or -1
Key Takeaway
🎯 Key Insight: Only 10 possible digits exist, so we can efficiently track which ones appear and find the second largest.
Asked in
Amazon 25 Google 18
28.4K Views
Medium Frequency
~10 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen