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:
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.
code[i] and businessLine[i] consist of printable ASCII characters.
isActive[i] is either true or false.
Solutions
Solution 1: Simulation
Thinking
With \(n\le 100\), filtering by the stated rules is enough. A valid coupon has a non-empty identifier of letters, digits, and underscores, a business line among the four allowed values, and an active flag.
Collect qualifying indices, sort them by \((\textit{businessLine},\textit{code})\), then emit the identifiers. The sort keys match the required category order and lexicographic tie-break.
We can directly simulate the conditions described in the problem to filter out valid coupons. The specific steps are as follows:
Check Identifier: For each coupon's identifier, check whether it is non-empty and contains only letters, digits, and underscores.
Check Business Category: Check whether each coupon's business category belongs to one of the four valid categories.
Check Activation Status: Check whether each coupon is active.
Collect Valid Coupons: Collect the ids of all coupons that satisfy the above conditions.
Sort: Sort the valid coupons by business category and identifier.
Return Result: Return the list of identifiers of the sorted valid coupons.
The time complexity is \(O(n \log n)\), and the space complexity is \(O(n)\), where \(n\) is the number of coupons.