Suppose you are getting ready for a camping trip and need to buy groceries at a supermarket. Every item in the store belongs to a department such as Dairy, Produce, or Pantry.
You are given:
products: a 2D list where each element is a pair [<productName>, <department>].shoppingList: a list of product names you plan to buy.If you shop in the same order as shoppingList, you might visit the same department several times. To reduce wasted time, you can instead group all needed products by department and visit each department only once.
Complete the function difference(product_categories, shopping_list) and return how many department visits are saved by grouping your shopping by department instead of following the original order in shoppingList.
Example 1:
Input:
products = [
["Cheese", "Dairy"],
["Carrots", "Produce"],
["Potatoes", "Produce"],
["Canned Tuna", "Pantry"],
["Romaine Lettuce", "Produce"],
["Chocolate Milk", "Dairy"],
["Flour", "Pantry"],
["Iceberg Lettuce", "Produce"],
["Coffee", "Pantry"],
["Pasta", "Pantry"],
["Milk", "Dairy"],
["Blueberries", "Produce"],
["Pasta Sauce", "Pantry"]],
shoppingList = ["Blueberries", "Milk", "Coffee", "Flour", "Cheese", "Carrots"]
Output: 2
Explanation: The original department order is Produce → Dairy → Pantry → Pantry → Dairy → Produce, which requires 5 visits. Grouping by department requires only 3 visits, so the number of saved visits is 5 - 3 = 2.
Constraints:
1 ≤ products.length ≤ 10^41 ≤ shoppingList.length ≤ 10^4