File: second-largest-digit-in-a-string/solution.py

Date: 2026-06-06

Time: 19:00

second-largest-digit-in-a-string/solution.py

Purpose

This file solves LeetCode 1796 — Second Largest Digit in a String. It owns a single responsibility: given an alphanumeric string, extract all unique digit characters and return the second-largest, or -1 if fewer than two distinct digits exist.

Key Components

second_highest(s: str) -> int — The sole public function.

Patterns

Set-based deduplication: Rather than sorting or maintaining a top-two tracker, the solution collects all digits into a set, which naturally deduplicates. This is a common idiom in this repo's easy-tier solutions — favor clarity and Python builtins over manual state management.

Two-pass max extraction: Instead of sorting the set (O(n log n)) or using heapq.nlargest, it calls max() twice with a remove() in between. This is O(n) in the size of the digit set, which is bounded at 10 elements — so performance is constant regardless of input length. The string scan itself is O(len(s)).

Dependencies

Imports: None — pure stdlib, no external or internal imports.

Imported by: The "Imported By" list in the prompt is misleading — those are test files across hundreds of other problems. They don't actually import this module. The only real consumer is second-largest-digit-in-a-string/test_solution.py, which tests this function directly.

Flow

1. Filter & convert: {int(c) for c in s if c.isdigit()} — single pass over the string, extracting digit characters and converting to int. The set comprehension deduplicates.

2. Early return: If the resulting set has fewer than 2 elements, return -1.

3. Remove max: digits.remove(max(digits)) mutates the set in-place, dropping the largest digit.

4. Return new max: max(digits) on the reduced set yields the second-largest.

Invariants

Error Handling

No exceptions are raised or caught. The -1 sentinel value serves as the error/absence signal, matching the LeetCode problem specification. The len(digits) < 2 check prevents max() from being called on an empty set after removal.

Topics to Explore

Beliefs