Problem Description
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist.
Key Insights
- Parse each character in the string and check if it is a digit.
- Store unique digit values using a set to avoid duplicates.
- Convert the set to a list and sort it in descending order.
- The second element in the sorted list is the second largest digit, if it exists.
Space and Time Complexity
Time Complexity: O(n) because we iterate through each character of the string. Space Complexity: O(1) since at most 10 unique digits are stored.
Solution
Traverse the alphanumeric string and extract the digit characters, converting them to integers and collecting them in a set to ensure their uniqueness. Then, if there are fewer than two unique digits, return -1. Otherwise, convert the set to a list, sort it in descending order, and retrieve the second largest digit. This approach covers the edge cases where duplicate digits might exist and ensures the correct second largest digit is returned.