Second Largest Digit in a String — LeetCode 1796 Python Solution

EasyHash TableString
Problem
#1796
Pattern
Hash Map
Reading time
2 min

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

Python
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 b

Complexity

MeasureComplexity
TimeO(n), where n is the length of the string s
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview