Second Largest Digit in a String

In this problem, we have to find the second largest numerical digit in a given alphanumeric string.

Here’s a step-by-step way to solve this problem:

  1. We initialize a set to hold the unique digits we find in the string. We’ll use a set because it automatically removes duplicates.

  2. We iterate over each character in the string. If the character is a digit, we add it to our set.

  3. After we’ve gone through the entire string, we’ll check the size of our set. If it has less than 2 elements, it means we don’t have a second largest digit, so we return -1.

  4. If our set has at least 2 elements, we sort it in descending order and return the second element (at index 1).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def secondHighest(self, s: str) -> int:
        # Initialize a set to hold the unique digits
        digits = set()

        # Iterate over each character in the string
        for ch in s:
            # If the character is a digit, add it to the set
            if ch.isdigit():
                digits.add(int(ch))

        # If there are less than 2 unique digits, return -1
        if len(digits) < 2:
            return -1
        
        # Otherwise, sort the digits in descending order and return the second one
        return sorted(digits, reverse=True)[1]

This solution works because it keeps track of all unique digits in the string and returns the second largest one. If no second largest digit exists, it correctly returns -1. The time complexity of this solution is O(n), where n is the length of the string, because we make a single pass through the string. The space complexity is O(1), because the set of digits can contain at most 10 elements.