#3606

Coupon Code Validator

Easy
ArrayHash TableStringSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

This approach efficiently filters and sorts valid coupons in one pass, leveraging a dictionary for business line priority.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a priority mapping for business lines.
  2. 2Step 2: Filter valid coupons and store them in a list with their business line.
  3. 3Step 3: Sort the list based on business line priority and code.
solution.py4 lines
1def validateCoupons(code, businessLine, isActive):
2    priority = {'electronics': 0, 'grocery': 1, 'pharmacy': 2, 'restaurant': 3}
3    validCoupons = [(businessLine[i], code[i]) for i in range(len(code)) if isActive[i] and code[i] and all(c.isalnum() or c == '_' for c in code[i]) and businessLine[i] in priority]
4    return [c for b, c in sorted(validCoupons, key=lambda x: (priority[x[0]], x[1]))]

Complexity note: Filtering is O(n) and sorting is O(n log n), leading to overall O(n log n).

  • 1Validating input is crucial.
  • 2Sorting can be optimized with priority mapping.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.