3606. Coupon Code Validator #2531
-
|
Topics: You are given three arrays of length
A coupon is considered valid if all of the following conditions hold:
Return an array of the codes of all valid coupons, sorted first by their businessLine in the order: Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to filter and sort coupon data based on specific validation rules. Let me break down the requirements and implement a solution. Approach:I'll follow these steps:
Let's implement this solution in PHP: 3606. Coupon Code Validator <?php
/**
* @param String[] $code
* @param String[] $businessLine
* @param Boolean[] $isActive
* @return String[]
*/
function validateCoupons($code, $businessLine, $isActive) {
$priority = ['electronics' => 0, 'grocery' => 1, 'pharmacy' => 2, 'restaurant' => 3];
// Collect valid coupons with their properties
$valid = [];
for ($i = 0; $i < count($code); $i++) {
if ($isActive[$i] &&
isset($priority[$businessLine[$i]]) &&
$code[$i] !== '' &&
preg_match('/^[a-zA-Z0-9_]+$/', $code[$i])) {
$valid[] = [
'code' => $code[$i],
'priority' => $priority[$businessLine[$i]]
];
}
}
// Sort and extract codes
usort($valid, fn($a, $b) =>
$a['priority'] <=> $b['priority'] ?: strcmp($a['code'], $b['code']));
return array_column($valid, 'code');
}
// Test cases
echo validateCoupons(["SAVE20","","PHARMA5","SAVE@20"], ["restaurant","grocery","pharmacy","restaurant"], [true,true,true,true]) . "\n"; // Output: ["PHARMA5","SAVE20"]
echo validateCoupons(["GROCERY15","ELECTRONICS_50","DISCOUNT10"], ["grocery","electronics","invalid"], [false,true,true]) . "\n"; // Output: ["ELECTRONICS_50"]
?>Explanation:
Complexity Analysis
|
Beta Was this translation helpful? Give feedback.
We need to filter and sort coupon data based on specific validation rules. Let me break down the requirements and implement a solution.
Approach:
I'll follow these steps:
Let's implement this solution in PHP: 3606. Coupon Code Validator