LeetCode 1796. Second Largest Digit in a String

Description

https://leetcode.com/problems/second-largest-digit-in-a-string/

Given an alphanumeric string `s`, return the second largest numerical digit that appears in `s`, or `-1` if it does not exist.

An alphanumericstring 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 <= 500`
• `s` consists of only lowercase English letters and/or digits.

Explanation

Create a set to store numerical digits and find out the second-largest number.

Python Solution

``````class Solution:
def secondHighest(self, s: str) -> int:
digit_set = set()
for c in s:
if c.isdigit():
digit_set.add(int(c))

if len(digit_set) < 2:
return -1

return sorted(list(digit_set))[-2]
``````
• Time Complexity: O(Nlog(N)).
• Space Complexity: O(N).