Second Largest Digit in a String - Complete Solution Guide
Second Largest Digit in a String is LeetCode problem 1796, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 <=
Detailed Explanation
The problem asks you to find the second largest digit in a given alphanumeric string. An alphanumeric string contains only lowercase English letters and digits. The function should return the second largest digit found in the string. If there is only one unique digit or no digits at all, it should return -1.
Solution Approach
The provided solutions use different approaches but achieve the same result. The Python solution utilizes a set to store unique digits, then sorts them in descending order to easily access the second largest. The Java, C++, and C solutions iteratively track the largest and second largest digits encountered, updating them as needed. Both approaches efficiently handle the problem.
Step-by-Step Algorithm
- Step 1: Iterate through the input string `s`.
- Step 2: For each character, check if it's a digit using `isdigit()` (or equivalent).
- Step 3: If it's a digit, convert it to an integer and either add it to a set (Python solution) or update the `largest` and `secondLargest` variables (Java, C++, C solutions).
- Step 4: (Python Solution) After iterating, check if the set has at least two elements. If not, return -1. Otherwise, sort the set and return the second element.
- Step 4: (Java, C++, C Solutions) After iterating, return the value of `secondLargest`.
Key Insights
- Insight 1: Using a set to store unique digits avoids duplicate counting and simplifies finding the second largest.
- Insight 2: Sorting the set of digits allows for easy retrieval of the second largest element.
- Insight 3: Handling edge cases where there are fewer than two unique digits is crucial (returning -1).
Complexity Analysis
Time Complexity: O(n + klogk)
Space Complexity: O(k)
Topics
This problem involves: Hash Table, String.
Companies
Asked at: Softwire.