1796. Second Largest Digit in a String

Description

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 1:

Input: s = "dfa12321afd"
Output: 2
Explanation: The digits that appear in s are [1, 2, 3]. The second largest digit is 2.

Example 2:

Input: s = "abc1111"
Output: -1
Explanation: The digits that appear in s are [1]. There is no second largest digit. 

Constraints:

  • 1 <= s.length <= 500

  • s consists of only lowercase English letters and/or digits.

Tags

String

Solution

This problem is similar to "find the second largest number", but requires the largest number is not equal to the second largest one. We initialize both the largest number first and the 2nd largest number second to -1. Iterave over the string and we only consider the case that the current character is a numeric byte/rune. We convert it from byte/rune to int type variable n.

  • If n > first, we pass the value of first to second, then assign n to first;

  • If n > second && n != first, we only update the value of second with n.

Finally, we return second.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(1)O(1)

Code

func secondHighest(s string) int {
	first, second := -1, -1
	for _, c := range s {
		if c >= '0' && c <= '9' {
			if n := int(c - '0'); n > first {
				second = first
				first = n
			} else if n > second && n != first {
				second = n
			}
		}
	}
	return second
}

Last updated

Was this helpful?