Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Validation and ordering are separate steps. First retain coupons satisfying every rule, then sort them by the prescribed business-category priority and by their code within a category.

Approach

Assign explicit ranks to electronics, grocery, pharmacy, and restaurant. For each coupon, require an active flag, a recognized business line, and a nonempty code consisting entirely of ASCII letters, digits, or underscores. A full-string match prevents accepting a valid-looking substring inside an invalid code.

Collect the valid code/category pairs. Python first sorts the pairs by code, then stably sorts by category rank. JavaScript uses one comparator that compares category ranks first and codes second. Both produce the required category-first, code-second order. Return only the codes from that list. Validation does not deduplicate coupons, so separate valid entries with the same code remain separate.

class Solution: def validateCoupons(self, code: List[str], businessLine: List[str], isActive: List[bool]) -> List[str]: n = len(code) b = {"electronics": 0, "grocery": 1, "pharmacy": 2, "restaurant": 3} res = [] for i in range(n): if fullmatch(r"[a-zA-Z0-9_]+", code[i]) and businessLine[i] in b and isActive[i]: res.append([code[i], businessLine[i]]) res.sort() res.sort(key = lambda x: b[x[1]]) out = [] for a, b in res: out.append(a) return out

Complexity analysis

Let n be the coupon count, C and H the total characters in codes and business-line strings, v the valid-coupon count, and L the longest valid code length (zero if none). Including validation, string-key lookup and lexicographic comparisons, a conservative time bound is O(n+C+H+vlog(v+1)(L+1)). Auxiliary space is O(v) for pairs, sorting and output references, excluding the input strings, which are not copied. The stated 100-character limits bound individual string costs, but comparisons are not inherently constant-time for unbounded strings.