2025-12-13 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp.
December LeetCoding Challenge 13
Description
Coupon Code Validator
You are given three arrays of length n that describe the properties of n coupons: code, businessLine, and isActive. The ith coupon has:
code[i]: a string representing the coupon identifier.businessLine[i]: a string denoting the business category of the coupon.isActive[i]: a boolean indicating whether the coupon is currently active.
A coupon is considered valid if all of the following conditions hold:
code[i]is non-empty and consists only of alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).businessLine[i]is one of the following four categories:"electronics","grocery","pharmacy","restaurant".isActive[i]is true.
Return an array of the codes of all valid coupons, sorted first by their businessLine in the order: "electronics", "grocery", "pharmacy", "restaurant", and then by code in lexicographical (ascending) order within each category.
Example 1:
Input: code = ["SAVE20","","PHARMA5","SAVE@20"], businessLine = ["restaurant","grocery","pharmacy","restaurant"], isActive = [true,true,true,true]
Output: ["PHARMA5","SAVE20"]
Explanation:
- First coupon is valid.
- Second coupon has empty code (invalid).
- Third coupon is valid.
- Fourth coupon has special character
@(invalid).
Example 2:
Input: code = ["GROCERY15","ELECTRONICS_50","DISCOUNT10"], businessLine = ["grocery","electronics","invalid"], isActive = [false,true,true]
Output: ["ELECTRONICS_50"]
Explanation:
- First coupon is inactive (invalid).
- Second coupon is valid.
- Third coupon has invalid business line (invalid).
Constraints:
n == code.length == businessLine.length == isActive.length1 <= n <= 1000 <= code[i].length, businessLine[i].length <= 100code[i]andbusinessLine[i]consist of printable ASCII characters.isActive[i]is eithertrueorfalse.
Solution
class Solution {
bool validCode(const string &code) {
if(code.empty()) return false;
for(auto c : code) {
if(c != '_' && !isalnum(c)) return false;
}
return true;
}
bool validBusinessLine(const string &businessLine) {
return businessLine == "electronics" || businessLine == "grocery" || businessLine == "pharmacy" || businessLine == "restaurant";
}
public:
vector<string> validateCoupons(vector<string>& code, vector<string>& businessLine, vector<bool>& isActive) {
int n = code.size();
vector<int> answerIndice;
for(int i = 0; i < n; ++i){
if(isActive[i] && validCode(code[i]) && validBusinessLine(businessLine[i])) answerIndice.push_back(i);
}
sort(answerIndice.begin(), answerIndice.end(), [&](int a, int b) {
return businessLine[a] < businessLine[b] || (businessLine[a] == businessLine[b] && code[a] < code[b]);
});
vector<string> answer;
for(auto index : answerIndice) {
answer.push_back(code[index]);
}
return answer;
}
};
// Accepted
// 779/779 cases passed (4 ms)
// Your runtime beats 69.53 % of cpp submissions
// Your memory usage beats 93.56 % of cpp submissions (66.8 MB)