Skip to main content

Coupon Code Validator - Solution & Explanation

EasyArrayHash TableStringSorting10 min readAsked at: Meta, Google
Practice this problem

Problem Statement

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:

  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:

  • First coupon is valid.
  • Second coupon has empty code (invalid).
  • Third coupon is valid.
  • Fourth coupon has special character @ (invalid).

Example 2:

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

Output: ["ELECTRONICS_50"]

Explanation:

  • First coupon is inactive (invalid).
  • Second coupon is valid.
  • Third coupon has invalid business line (invalid).

 

Constraints:

  • n == code.length == businessLine.length == isActive.length
  • 1 <= n <= 100
  • 0 <= code[i].length, businessLine[i].length <= 100
  • code[i] and businessLine[i] consist of printable ASCII characters.
  • isActive[i] is either true or false.

Approach Overview

Problem Overview: You receive a list of coupon codes and need to determine which ones are valid based on a set of rules such as formatting constraints, character checks, and duplicate detection. The goal is to process each code efficiently and return only the coupons that satisfy the validation rules.

Approach 1: Basic Simulation (O(n * k), O(1) space)

The most direct solution iterates through every coupon string and validates it character by character. You check conditions like allowed characters, length constraints, and formatting rules using simple loops. This approach treats each coupon independently and uses conditional checks to determine whether the code should be accepted or rejected. Time complexity is O(n * k) where n is the number of coupons and k is the length of each coupon string, while extra space remains O(1) because validation happens in-place without additional data structures. This works well when the rules are simple and the dataset is small.

Approach 2: Hash Table for Duplicate Detection (O(n * k), O(n) space)

If coupon validity requires detecting duplicates or repeated codes, a hash table improves efficiency. As you iterate through the list, normalize the coupon (for example by converting to lowercase or trimming whitespace) and store it in a hash set. A constant-time lookup quickly tells you if the code already appeared earlier. The validation still scans each string once, keeping time complexity at O(n * k), but space increases to O(n) for storing previously seen coupons. This pattern is common in problems involving uniqueness checks across arrays.

Approach 3: Sorting-Based Canonical Validation (O(n * k log k), O(n) space)

Some validation rules treat coupons with the same characters as equivalent regardless of order. In that case, convert each string into a canonical form by sorting its characters. Two coupons with identical sorted representations are effectively duplicates. This uses string manipulation and sorting. For each coupon you sort its characters in O(k log k), then store the canonical version in a hash set. Overall complexity becomes O(n * k log k) time and O(n) space. The benefit is simpler duplicate detection for permutation-based rules.

Recommended for interviews: Start by explaining the basic simulation since it mirrors the problem statement and demonstrates clear reasoning. Then improve it using a hash set to track duplicates or normalized forms of coupons. Interviewers usually expect the hash-table-based approach because it maintains linear processing of the input while ensuring efficient lookups.

Solution

We can directly simulate the conditions described in the problem to filter out valid coupons. The specific steps are as follows:

  1. Check Identifier: For each coupon's identifier, check whether it is non-empty and contains only letters, digits, and underscores.
  2. Check Business Category: Check whether each coupon's business category belongs to one of the four valid categories.
  3. Check Activation Status: Check whether each coupon is active.
  4. Collect Valid Coupons: Collect the ids of all coupons that satisfy the above conditions.
  5. Sort: Sort the valid coupons by business category and identifier.
  6. Return Result: Return the list of identifiers of the sorted valid coupons.

The time complexity is O(n times log n), and the space complexity is O(n), where n is the number of coupons.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Basic SimulationO(n * k)O(1)When only format or character validation is required and no duplicate tracking is needed
Hash Table ValidationO(n * k)O(n)General case where coupon uniqueness or repeated detection is required
Sorting Canonical FormO(n * k log k)O(n)When coupons should be treated as equivalent regardless of character order

Video Solution

Coupon Code Validator | Simple Explanation | Leetcode 3606 | codestorywithMIK • codestorywithMIK • 3,261 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Coupon Code Validator easy or hard?
Coupon Code Validator is considered an Easy problem because the solution mainly requires straightforward iteration and basic data structures like sets. The main challenge is carefully implementing the validation rules while keeping the solution efficient.
Coupon Code Validator Python/Java solution
In Python, the solution typically uses a set to track seen coupon codes while iterating through the list and validating each string. In Java, a HashSet<String> performs the same role. Both implementations maintain O(n * k) time complexity with straightforward string checks and constant-time set lookups.
How to solve Coupon Code Validator in O(n)?
Process each coupon once and store previously validated codes in a hash set. Each string is scanned to ensure it follows the required format, then inserted into the set if it is unique. Because hash lookups are constant time on average, the algorithm scales linearly with the number of coupons, giving O(n * k) complexity for full validation.
What is the best approach for Coupon Code Validator?
The hash-table-based simulation is usually the best approach. Iterate through each coupon string, normalize it if needed, and store it in a hash set to detect duplicates or invalid repetitions. This keeps processing linear with O(n * k) time and O(n) space while keeping the logic simple and easy to implement in interviews.
Is Coupon Code Validator asked at Google/Amazon/Meta?
Problems involving string validation, hash tables, and duplicate detection appear frequently in coding interviews at companies like Amazon, Google, and Meta. While this exact problem may vary in wording, the underlying pattern of validating strings and using hash sets to enforce uniqueness is very common.
What data structure is used in Coupon Code Validator?
The primary data structure is a hash set or hash map used to track previously processed coupon codes. The solution also relies on string processing and sometimes sorting to normalize codes before comparison. Arrays are used to store and iterate through the list of coupons.
What is the time complexity of Coupon Code Validator?
The typical solution runs in O(n * k) time where n is the number of coupons and k is the length of each coupon string. Each code is scanned once for validation, and hash table lookups run in average O(1) time. If sorting is used to create canonical forms, the complexity becomes O(n * k log k).

Ready to solve this problem?

Practice Coupon Code Validator with our built-in code editor and test cases.

Practice on FleetCode