Second Largest Digit in a String Problem
#1796
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1796.
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.
Example 1:
Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Example 2:
Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit.
Constraints:
1 <= s.length <= 500sconsists of only lowercase English letters and digits.
Solution
Approach: One Pass
Keep the largest digit a and the second largest distinct digit b seen so far, both starting at -1. For each digit v in the string: if v > a, then a becomes the new second largest and v the new largest; otherwise, if b < v < a, update b = v. Equal digits change nothing. Return b.
Complexity: time O(n), space O(1), where n is the length of s.
class Solution:
def secondHighest(self, s: str) -> int:
a = b = -1
for c in s:
if c.isdigit():
v = int(c)
if v > a:
a, b = v, a
elif b < v < a:
b = v
return b