Last active
December 13, 2025 17:55
-
-
Save tatsuyax25/a616b9f6737f46d253cc0f9c40265a8e to your computer and use it in GitHub Desktop.
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string[]} code | |
| * @param {string[]} businessLine | |
| * @param {boolean[]} isActive | |
| * @return {string[]} | |
| */ | |
| var validateCoupons = function(code, businessLine, isActive) { | |
| // Guard: ensure arrays exist and have equal length | |
| if (!Array.isArray(code) || !Array.isArray(businessLine) || !Array.isArray(isActive)) return []; | |
| const n = Math.min(code.length, businessLine.length, isActive.length); | |
| if (n === 0) return []; | |
| // Fixed category order and a lookup for O(1) indexing | |
| const orderedCategories = ["electronics", "grocery", "pharmacy", "restaurant"]; | |
| const categoryIndex = { | |
| electronics: 0, | |
| grocery: 1, | |
| pharmacy: 2, | |
| restaurant: 3 | |
| }; | |
| // Buckets per category to ensure stable concatenation in the requested order | |
| const buckets = { | |
| electronics: [], | |
| grocery: [], | |
| pharmacy: [], | |
| restaurant: [] | |
| }; | |
| // Strict code validation: non-empty, alphanumeric + underscore only | |
| const isValidCode = (s) => { | |
| if (typeof s !== "string") return false; | |
| if (s.length === 0) return false; // no trimming per spec; empty string is invalid | |
| return /^[A-Za-z0-9_]+$/.test(s); | |
| }; | |
| // Validate and bucket | |
| for (let i = 0; i < n; i++) { | |
| const c = code[i]; | |
| const b = businessLine[i]; | |
| const active = isActive[i]; | |
| // businessLine must be exactly one of the four (case-sensitive match) | |
| if (!Object.prototype.hasOwnProperty.call(categoryIndex, b)) continue; | |
| // isActive must be strictly true (not truthy strings like "true") | |
| if (active !== true) continue; | |
| if (!isValidCode(c)) continue; | |
| buckets[b].push(c); | |
| } | |
| // Deterministic ASCII lexicographical sort (case-sensitive) | |
| // Using direct < and > avoids locale variations. | |
| const sortCodes = (arr) => arr.sort((x, y) => (x < y ? -1 : x > y ? 1 : 0)); | |
| // Sort each bucket and concatenate in the specified category order | |
| const result = []; | |
| for (const cat of orderedCategories) { | |
| sortCodes(buckets[cat]); | |
| // Append codes in order | |
| for (const c of buckets[cat]) result.push(c); | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment