This question evaluates understanding of rule-based filtering for a single-rule ad filter, including set containment for locations, numeric range checks for age, handling of optional constraints, and operator logic (AND/OR).
When a user watches content, the system needs to filter an ad pool to find ads that match one rule. Implement a lightweight filter that supports a single rule with an operator.
Ad
id: String
targetLocations: Set<String>
(e.g.,
{ "CA", "TX" }
)
age: int
(intended viewer age for the ad)
Rule
targetLocations: Set<String>
(optional)
minAge: Integer
(optional)
maxAge: Integer
(optional)
operator: "AND" | "OR"
rule.targetLocations
is present and non-empty, then an ad matches the location constraint if
rule.targetLocations ⊆ ad.targetLocations
(i.e., the ad targets
all
locations required by the rule).
rule.minAge
is present, require
ad.age >= rule.minAge
rule.maxAge
is present, require
ad.age <= rule.maxAge
rule.operator
:
AND
: ad must satisfy
all
present constraints
OR
: ad must satisfy
at least one
present constraint
List<Ad> ads
,
Rule rule
List<String>
of matching
ad.id
values,
preserving the original input order
Rule: minAge = 21, targetLocations = {"US"}, operator = AND
Ads:
A
:
age=21
,
targetLocations={"US","CA"}
→ match
B
:
age=13
,
targetLocations={"US"}
→ no (age)
C
:
age=25
,
targetLocations={"CA"}
→ no (location)
Output: ["A"]
ads.length
can be large; keep it efficient.