Skip to main content
Back to problems
#3606
Easy Algorithms

Coupon code validator

Array Hash Table String Sorting
65.0% acceptance
Feb 25, 2026
332
107
You are given three arrays of length n that describe the properties of n coupons: code, businessLine, and isActive. The ith coupon has: code[i]: a string representing the coupon identifier. businessLine[i]: a string denoting the business category of the coupon. isActive[i]: a boolean indicating whether the coupon is currently active. A coupon is considered valid if all of the following conditions hold: code[i] is non-empty and consists only of alphanumeric characters (a-z, A-Z, 0-9) and underscores (_). businessLine[i] is one of the following four categories: "electronics", "grocery", "pharmacy", "restaurant". 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.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn validate_coupons(code: Vec<String>, business_line: Vec<String>, is_active: Vec<bool>) -> Vec<String> {
    let order = |bl: &str| -> Option<usize> {
      match bl {
        "electronics" => Some(0),
        "grocery"     => Some(1),
        "pharmacy"    => Some(2),
        "restaurant"  => Some(3),
        _             => None,
      }
    };
    let valid_code = |c: &str| -> bool {
      !c.is_empty() && c.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_')
    };
    let n = code.len();
    let mut result: Vec<(usize, String)> = Vec::new();
    for i in 0..n {
      if !is_active[i] { continue; }
      if !valid_code(&code[i]) { continue; }
      if let Some(ord) = order(&business_line[i]) {
        result.push((ord, code[i].clone()));
      }
    }
    result.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    result.into_iter().map(|(_, c)| c).collect()
  }
}