Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created December 13, 2025 22:32
Show Gist options
  • Select an option

  • Save Ifihan/4e652bd3f7a4a9c7ae6c5c9e6b19d4a4 to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/4e652bd3f7a4a9c7ae6c5c9e6b19d4a4 to your computer and use it in GitHub Desktop.
Coupon Code Validator

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n · L + n log n),
  • Space: O(n)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment