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
๐Ÿ† Digital Medal CeremonyInput String: "dfa12321afd"Scanning for digit contestants...๐Ÿฅ‡Gold: 3๐ŸฅˆSilver: 2๐Ÿฅ‰Bronze: 1๐ŸŽฏ Result: Silver Medal WinnerSecond Largest Digit = 2Found in O(n) time, O(1) space!
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!
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.0K Views
Medium Frequency
~15 min Avg. Time
850 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