Skip to main content
Back to problems
Leetcode
Medium
Strings
Arrays
Math
Second Largest Digit In A String

Find the second largest numeric digit that appears in a string.

Acceptance 0%
Problem Statement

Given a string s, scan all characters and consider only the digits '0' through '9'.

Return the second largest distinct digit that appears in s. If fewer than two distinct digits appear, return -1.

A digit is counted by its numeric value, and repeated digits only matter once for determining distinct values.

Input Format

  • s: a string containing lowercase letters, digits, or other characters depending on the platform variant.

Treat only characters '0' to '9' as digits.

Output Format

Return the second largest distinct digit present in the string, or -1 if it does not exist.

Constraints

  • Scan the string once if possible.
  • Distinct digit values only.
  • If there is no second distinct digit, return -1.
Examples
Sample cases returned by the problem API.

Example 1

Input

s = "dfa12321afd"

Output

2

Explanation

The distinct digits are 1, 2, and 3. The largest is 3 and the second largest is 2.

Example 2

Input

s = "abc1111"

Output

-1

Explanation

Only one distinct digit appears: 1.

Show 1 more example

Example 3

Input

s = "ck077"

Output

0

Explanation

The distinct digits are 0 and 7. The largest is 7 and the second largest is 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.