[LeetCode] Coupon Code Validator

3606. Coupon Code Validator

You are given three arrays of length n that describe the properties of n coupons: code, businessLine, and isActive. The ithcoupon 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:

  1. code[i] is non-empty and consists only of alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).
  2. businessLine[i] is one of the following four categories: "electronics", "grocery", "pharmacy", "restaurant".
  3. 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
unordered_set<string> allowCategories{"restaurant", "grocery", "pharmacy", "electronics"};
public:
vector<string> validateCoupons(vector<string>& code, vector<string>& businessLine, vector<bool>& isActive) {
vector<string> res;
unordered_map<string, vector<string>> mp;
for(int i = 0; i < code.size(); i++) {
if(!isActive[i]) continue;
if(!allowCategories.count(businessLine[i])) continue;
if(code[i] == "") continue;
bool ok = true;
for(auto& ch : code[i]) {
if(isalpha(ch)) continue;
if(isdigit(ch)) continue;
if(ch == '_') continue;
ok = false;
break;
}
if(ok) {
mp[businessLine[i]].push_back(code[i]);
}
}
for(auto& k : {"electronics", "grocery", "pharmacy", "restaurant"}) {
sort(begin(mp[k]), end(mp[k]));
for(auto& s : mp[k]) res.push_back(s);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/08/PS/LeetCode/coupon-code-validator/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.