Second Largest Digit in a String — LeetCode 1796 Python Solution
- Problem
- #1796
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an alphanumeric string s, return the second largest numerical digit that appears in s, or -1 if it does not exist. An alphanumeric string is a string consisting of lowercase English letters and digits.
Example
- Input
- s = "dfa12321afd"
- Output
- 2
- Explanation
- The digits that appear in s are [1, 2, 3]. The second largest digit is 2.
Python solution
class Solution:
def secondHighest(self, s: str) -> int:
a = b = -1
for c in s:
if c.isdigit():
v = int(c)
if v > a:
a, b = v, a
elif b < v < a:
b = v
return bComplexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1796. Second Largest Digit in a String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1796. Second Largest Digit in a String?
- LeetCode 1796. Second Largest Digit in a String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1796. Second Largest Digit in a String?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 1796. Second Largest Digit in a String?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1796. Second Largest Digit in a String cover?
- LeetCode 1796. Second Largest Digit in a String is tagged Hash Table and String on LeetCode.