Approach
Sorting and greedy selection
For Coupon Code Validator, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 27 lines of C++ from the credited upstream file coupon-code-validator.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 vector<string> validateCoupons(vector<string>& code, vector<string>& businessLine, vector<bool>& isActive) {8 static const unordered_map<string, int> LOOKUP = {{"electronics", 0}, {"grocery", 1}, {"pharmacy", 2}, {"restaurant", 3}};9 10 vector<pair<int, string>> sorted_codes;11 for (int i = 0; i < size(code); ++i) {12 if (isActive[i] && !empty(code[i]) && LOOKUP.count(businessLine[i]) && all_of(cbegin(code[i]), cend(code[i]), [](const auto& x) {13 return isalnum(x) || x == '_';14 })) {15 sorted_codes.emplace_back(LOOKUP.at(businessLine[i]), code[i]);16 }17 }18 sort(begin(sorted_codes), end(sorted_codes));19 vector<string> result;20 result.reserve(size(sorted_codes));21 for (const auto& [_, c] : sorted_codes) {22 result.emplace_back(c);23 }24 return result;25 }26};27