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 a String INPUT Alphanumeric String s: d f a 1 2 3 2 1 a f d = Digit = Letter Digits Found: 1, 2, 3, 2, 1 Unique Digits: 1, 2, 3 ALGORITHM STEPS 1 Initialize Variables largest = -1, second = -1 2 Iterate Through String Check if char is digit 3 Update Two Variables If digit > largest: second = largest largest = digit 4 Handle Second Case Else if digit > second and digit != largest: second = digit Variable Tracking: After '1': L=1, S=-1 After '2': L=2, S=1 After '3': L=3, S=2 Final: L=3, S=2 FINAL RESULT Second Largest Digit: 2 From digits {1, 2, 3}: 1st Largest: 3 2nd Largest: 2 [OK] 3rd Largest: 1 Output: 2 Key Insight: Single pass with two variables (largest, second) achieves O(n) time complexity. When a new largest is found, the old largest becomes the second largest. Space complexity is O(1) - only two integer variables needed regardless of input size. TutorialsPoint - Second Largest Digit in a String | Single Pass Two Variables Approach
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