LeetCode 1796: Second Largest Digit in a String Solution
Master LeetCode problem 1796 (Second Largest Digit in a String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1796. Second Largest Digit in a String
Problem Explanation
Explanation
To solve this problem, we can iterate through the given string s and keep track of the unique numerical digits we encounter. We can store these digits in a set to ensure uniqueness. Once we have all unique digits, we can sort them in descending order and return the second largest digit if it exists.
- Time complexity: O(n) where n is the length of the input string
s. - Space complexity: O(1) since we are using a set to store at most 10 unique digits.
Solution Code
class Solution {
public int secondHighest(String s) {
Set<Integer> digits = new HashSet<>();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
digits.add(Character.getNumericValue(c));
}
}
List<Integer> sortedDigits = new ArrayList<>(digits);
Collections.sort(sortedDigits, Collections.reverseOrder());
if (sortedDigits.size() < 2) {
return -1;
}
return sortedDigits.get(1);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1796 (Second Largest Digit in a String)?
This page provides optimized solutions for LeetCode problem 1796 (Second Largest Digit in a String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1796 (Second Largest Digit in a String)?
The time complexity for LeetCode 1796 (Second Largest Digit in a String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1796 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1796 in Java, C++, or Python.