Similar Problems
Similar Problems not available
Second Largest Digit In A String - Leetcode Solution
Companies:
LeetCode: Second Largest Digit In A String Leetcode Solution
Difficulty: Easy
Topics: string hash-table
Problem Statement:
Given a string s consisting of lowercase English letters and digits, find the second largest digit in s.
If there is no second largest digit in s, return -1.
Example 1:
Input: s = "abc1111" Output: -1 Explanation: The only digit in s is 1, which is the largest one.
Example 2:
Input: s = "aab34" Output: 3 Explanation: The largest digit is 4, and the second largest digit is 3.
Approach:
The approach to solving this problem would be as follows:
We can loop through the string, and whenever we encounter a digit, we can add it to a set.
Then we can sort the set in descending order, and we can return the second element of the set.
If there is no second element, then we have only encountered one digit in the string, and so we return -1.
Code:
Here is the Python code for the solution to this problem:
def secondHighest(s): digits = set()
for char in s: if char.isdigit(): digits.add(int(char))
digits = sorted(digits, reverse=True)
if len(digits) < 2: return -1
return digits[1]
Explanation of the code:
We define the function secondHighest, which takes the string s as its input.
We then create an empty set named “digits”.
Next, we loop through each character in the string s.
If the character is a digit (i.e., char.isdigit()), we add it as an integer to the set “digits”.
Then we sort the set “digits” in reverse order.
If the length of the set “digits” is less than 2, it means that we have not encountered a second digit in the string s, and so we return -1.
Otherwise, we return the second element of the sorted set “digits”.
Complexity:
The time complexity of this solution is O(nlogn), where n is the length of the string s. The reason for this is that sorting the set takes O(nlogn) time.
The space complexity of this solution is O(n), as we are adding each digit of the string to the set “digits”.
Second Largest Digit In A String Solution Code
1