Second Largest Digit in a String - Problem
Given an alphanumeric string s, you need to find the second largest numerical digit that appears in the string. If no second largest digit exists, return -1.
An alphanumeric string consists of lowercase English letters and digits (0-9). Your task is to ignore all letters and focus only on the numerical digits present in the string.
Key Points:
- Only consider digits (0-9), ignore all letters
- Find the second largest unique digit
- If there are fewer than 2 unique digits, return -1
- Duplicate digits are treated as the same value
Example: In string "dfa12321afd", the digits are [1,2,3,2,1]. Unique digits in descending order: [3,2,1]. The second largest is 2.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "dfa12321afd"
โบ
Output:
2
๐ก Note:
The digits in the string are [1,2,3,2,1]. The unique digits in descending order are [3,2,1]. The second largest unique digit is 2.
example_2.py โ Single Digit
$
Input:
s = "abc1111"
โบ
Output:
-1
๐ก Note:
The only digit present is 1. Since there's only one unique digit, there is no second largest digit, so we return -1.
example_3.py โ No Digits
$
Input:
s = "abcdef"
โบ
Output:
-1
๐ก Note:
There are no digits in the string, only letters. Since we need at least 2 unique digits to find a second largest, we return -1.
Constraints
- 1 โค s.length โค 500
- s consists of only lowercase English letters and digits
- Return -1 if no second largest digit exists
Visualization
Tap to expand
Understanding the Visualization
1
Setup Podium
Initialize gold and silver positions as empty (-1)
2
Contestants Arrive
Each digit in the string steps forward to compete
3
Medal Assignment
If a digit beats the current gold medalist, gold moves to silver and new digit takes gold
4
Award Ceremony
Return the silver medalist (second largest) or -1 if no silver exists
Key Takeaway
๐ฏ Key Insight: We only need to track the top 2 performers (digits) as we scan through the contestants (string), making this an optimal O(n) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code