← All problems

3606. Coupon Code Validator

EasyOpen on LeetCodeProblem statement

Problem Statement

3606. Coupon Code Validator

Easy


You are given three arrays of length n that describe the properties of n coupons: code, businessLine, and isActive. The ith coupon has:

A coupon is considered valid if all of the following conditions hold:

  1. code[i] is non-empty and consists only of alphanumeric characters (a-z, A-Z, 0-9) and underscores (_).
  2. businessLine[i] is one of the following four categories: "electronics", "grocery", "pharmacy", "restaurant".
  3. 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.

 

Example 1:

Input: code = ["SAVE20","","PHARMA5","SAVE@20"], businessLine = ["restaurant","grocery","pharmacy","restaurant"], isActive = [true,true,true,true]

Output: ["PHARMA5","SAVE20"]

Explanation:

Example 2:

Input: code = ["GROCERY15","ELECTRONICS_50","DISCOUNT10"], businessLine = ["grocery","electronics","invalid"], isActive = [false,true,true]

Output: ["ELECTRONICS_50"]

Explanation:

 

Constraints:

Java

Source file
class Solution {
    public List<String> validateCoupons(String[] code, String[] businessLine, boolean[] isActive) {
        int n = code.length;
        List<String> ans = new ArrayList<>();
        Queue<String[]> pq = new PriorityQueue<>((a, b) -> a[1].equals(b[1])
                ? a[0].compareTo(b[0])
                : a[1].compareTo(b[1]));
        Set<String> bizLines = new HashSet<>();
        bizLines.addAll(Arrays.asList("electronics", "grocery", "pharmacy", "restaurant"));
        for (int i = 0; i < n; i++) {
            if (isValid(code[i], businessLine[i], isActive[i], bizLines))
                pq.offer(new String[] { code[i], businessLine[i] });
        }
        while (!pq.isEmpty())
            ans.add(pq.poll()[0]);
        return ans;
    }

    private boolean isValid(String code, String bizLine, boolean isActive, Set<String> bizLines) {
        if (!isActive)
            return false;
        if (!bizLines.contains(bizLine))
            return false;
        if (code.length() == 0)
            return false;
        code = code.toLowerCase();
        for (char c : code.toCharArray()) {
            if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')
                continue;
            return false;
        }
        return true;
    }
}