Leetcode 1796. Second Largest Digit in a String
You are given a string s
which consists of only digits and lowercase English letters. Your task is to return the second largest digit in the string. If there is no such digit, return -1
.
-1
.-1
.#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <algorithm>
int secondHighest(const std::string& s) {
std::set<int> digitSet;
// Step 1: Collect digits from the string
for(char ch : s) {
if(isdigit(ch)) {
digitSet.insert(ch - '0'); // Convert char digit to int and insert into set
}
}
// Step 2: Check if we have enough unique digits
if(digitSet.size() < 2) {
return -1;
}
// Step 3: Find the second largest unique digit
std::vector<int> digits(digitSet.begin(), digitSet.end());
std::sort(digits.rbegin(), digits.rend()); // Sort in descending order
return digits[1]; // Return the second largest digit
}
int main() {
// Test cases
std::string test1 = "dfa12321afd";
std::cout << "Second largest digit in \"" << test1 << "\": " << secondHighest(test1) << std::endl;
std::string test2 = "abc1111";
std::cout << "Second largest digit in \"" << test2 << "\": " << secondHighest(test2) << std::endl;
std::string test3 = "a5b6c7";
std::cout << "Second largest digit in \"" << test3 << "\": " << secondHighest(test3) << std::endl;
return 0;
}
s
as we scan through the entire string once.Therefore, the time complexity for this approach is O(n), where n is the length of the string. The space complexity is O(1) because the set of unique digits is at most size 10.
Feel free to ask if you need further clarifications or have additional requirements!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?