#1796
Second Largest Digit in a String
EasyHash TableStringHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(n) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a set to collect digits while iterating through the string, then directly finds the second largest without sorting. This is more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a set to collect unique digits.
- 2Step 2: Iterate through each character in the string. If it's a digit, add it to the set.
- 3Step 3: Convert the set to a list and check its size. If less than 2, return -1.
- 4Step 4: Find the maximum digit, remove it, and find the new maximum, which is the second largest.
solution.py12 lines
1# Full working Python code
2
3def second_largest_digit(s):
4 digits = set()
5 for char in s:
6 if char.isdigit():
7 digits.add(int(char))
8 if len(digits) < 2:
9 return -1
10 max_digit = max(digits)
11 digits.remove(max_digit)
12 return max(digits)ℹ
Complexity note: The time complexity is O(n) because we only iterate through the string once and perform constant-time operations with the set. The space complexity is O(n) for storing the digits.
- 1Using a set helps to automatically handle duplicates.
- 2Finding the maximum and then the second maximum is efficient.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.