You are given a list of products, where each product is represented as [id, [tag1, tag2, ...]], and a list user_tags holding a user's interests based on their purchase history or preferences.
Return a list of product ids sorted by relevance. The relevance of a product is the number of matching tags between the product and the user's interests. Only include products that have at least one matching tag.
If two products have the same relevance score, return them in ascending order of product id.
Function Signature
def recommend_products(products: list[list], user_tags: list[str]) -> list[int]:
Rules
-
Each
products[i]
is a two-element list: an integer product id, then a list of tag strings.
-
A tag matches when it appears both in the product's tags and in
user_tags
. Relevance is the number of distinct matching tags.
-
Sort by relevance from highest to lowest, then by product id ascending. Product ids are unique, so the order is fully determined.
-
If no product has a matching tag, return an empty list.
Constraints
-
1 <= len(products) <= 10^4
-
Product ids are unique positive integers.
-
Each product has between 1 and 20 tags.
-
1 <= len(user_tags) <= 20
-
All tags are lowercase English strings of length 1 to 20.
Examples
Input:
products = [
[1, ["electronics", "gaming", "laptop"]],
[2, ["books", "fiction", "mystery"]],
[3, ["electronics", "phone", "accessories"]],
[4, ["gaming", "console", "accessories"]],
[5, ["books", "science", "education"]]
]
user_tags = ["electronics", "gaming", "accessories"]
Output: [1, 3, 4]
Product 1 matches electronics and gaming, product 3 matches electronics and accessories, and product 4 matches gaming and accessories, so all three score 2. Products 2 and 5 match nothing and are left out, and the three tied products come back in ascending id order.
Input:
products = [
[10, ["cooking", "italian", "pasta"]],
[20, ["cooking", "french", "baking"]],
[30, ["fitness", "yoga"]],
[40, ["cooking", "italian", "baking", "french"]]
]
user_tags = ["cooking", "italian"]
Output: [10, 40, 20]
Products 10 and 40 match cooking and italian (score 2), product 20 matches only cooking (score 1), and product 30 matches nothing. The tie between 10 and 40 is broken by id, and both come before 20.
Input:
products = [[5, ["tea"]], [2, ["coffee", "tea"]]]
user_tags = ["juice"]
Output: []
Neither product shares a tag with the user, so the result is empty.