I iterate through all coupons and keep only those that satisfy all validity rules: the coupon must be active, its business line must be one of the allowed categories, and its code must be non-empty and contain only alphanumeric characters or underscores. While filtering, I group valid coupon codes by their business line. Finally, I output the result by traversing the business lines in the required fixed order and appending the codes in lexicographical order within each category.
class Solution:
def validateCoupons(self, code: List[str], businessLine: List[str], isActive: List[bool]) -> List[str]:
allowed_lines = ["electronics", "grocery", "pharmacy", "restaurant"]
order_index = {b: i for i, b in enumerate(allowed_lines)}
buckets = {b: [] for b in allowed_lines}
pattern = re.compile(r'^[A-Za-z0-9_]+$')
for c, b, active in zip(code, businessLine, isActive):
if not active:
continue
if b not in order_index:
continue
if not c or not pattern.match(c):
continue
buckets[b].append(c)
result = []
for b in allowed_lines:
result.extend(sorted(buckets[b]))
return result- Time: O(n · L + n log n),
- Space: O(n)