We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Second Largest Digit in a String

Number: 1904

Difficulty: Easy

Paid? No

Companies: Softwire


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.


Code Solutions

# Define a function to find the second largest digit in the string
def secondHighest(s: str) -> int:
    # Create a set to store unique digit values
    unique_digits = set()
    
    # Iterate over each character in string s
    for char in s:
        if char.isdigit():  # Check if the character is numeric
            unique_digits.add(int(char))  # Convert character to int and add to the set

    # If there are fewer than two unique digits, return -1
    if len(unique_digits) < 2:
        return -1

    # Sort unique digits in descending order
    sorted_digits = sorted(unique_digits, reverse=True)
    
    # The second element is the second largest digit
    return sorted_digits[1]

# Example usage:
print(secondHighest("dfa12321afd"))  # Output should be 2
print(secondHighest("abc1111"))      # Output should be -1
← Back to All Questions