Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1796.html

1796. Second Largest Digit in a String

Level

Easy

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.

Solution

Loop over s and count the occurrences of all digits. Then loop over all digits backwards and find the second largest digit that has occurrence greater than 0. If such a digit exists, return the digit. Otherwise, return -1.

  • class Solution {
        public int secondHighest(String s) {
            int[] counts = new int[10];
            int length = s.length();
            for (int i = 0; i < length; i++) {
                char c = s.charAt(i);
                if (c >= '0' && c <= '9')
                    counts[c - '0']++;
            }
            boolean flag = false;
            for (int i = 9; i >= 0; i--) {
                if (counts[i] > 0) {
                    if (!flag)
                        flag = true;
                    else
                        return i;
                }
            }
            return -1;
        }
    }
    
    ############
    
    class Solution {
        public int secondHighest(String s) {
            int a = -1, b = -1;
            for (int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                if (Character.isDigit(c)) {
                    int v = c - '0';
                    if (v > a) {
                        b = a;
                        a = v;
                    } else if (v > b && v < a) {
                        b = v;
                    }
                }
            }
            return b;
        }
    }
    
  • // OJ: https://leetcode.com/problems/second-largest-digit-in-a-string
    // Time: O(N)
    // Space: O(1)
    class Solution {
    public:
        int secondHighest(string s) {
            set<int> st;
            for (char c : s) {
                if (isdigit(c)) st.insert(c - '0');
            }
            if (st.size() < 2) return -1;
            return *next(st.rbegin());
        }
    };
    
  • 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
    
    ############
    
    # 1796. Second Largest Digit in a String
    # https://leetcode.com/problems/second-largest-digit-in-a-string
    
    class Solution:
        def secondHighest(self, s: str) -> int:
            res = set(list(c for c in s if c.isdigit()))
        
            return sorted(list(res))[-2] if len(res) > 1 else -1
    
    
  • func secondHighest(s string) int {
    	a, b := -1, -1
    	for _, c := range s {
    		if c >= '0' && c <= '9' {
    			v := int(c - '0')
    			if v > a {
    				b, a = a, v
    			} else if v > b && v < a {
    				b = v
    			}
    		}
    	}
    	return b
    }
    
  • function secondHighest(s: string): number {
        let first = -1;
        let second = -1;
        for (const c of s) {
            if (c >= '0' && c <= '9') {
                const num = c.charCodeAt(0) - '0'.charCodeAt(0);
                if (first < num) {
                    [first, second] = [num, first];
                } else if (first !== num && second < num) {
                    second = num;
                }
            }
        }
        return second;
    }
    
    
  • impl Solution {
        pub fn second_highest(s: String) -> i32 {
            let mut first = -1;
            let mut second = -1;
            for c in s.as_bytes() {
                if char::is_digit(*c as char, 10) {
                    let num = (c - b'0') as i32;
                    if first < num {
                        second = first;
                        first = num;
                    } else if num < first && second < num {
                        second = num;
                    }
                }
            }
            second
        }
    }
    
    

All Problems

All Solutions