Similar Problems

Similar Problems not available

Reducing Dishes

Companies:

LeetCode:  Reducing Dishes Leetcode Solution

Difficulty: Unknown

Topics: not-available  

Problem Statement:

Given a group of dishes represented by a list of strings, each containing at least one ingredient, you need to find the dishes that have at least 2 identical ingredients and group them together.

Return a list of lists where each list contains all the grouped dishes.

You can return the answer in any order.

Example:

Input: dishes = [["Salad","Tomato","Cucumber","Salad","Sauce"], ["Pizza","Tomato","Sausage","Sauce","Dough"], ["Quesadilla","Chicken","Cheese","Sauce"], ["Sandwich","Salad","Bread","Tomato","Cheese"]]

Output: [["Cheese","Pizza","Quesadilla"],["Salad","Salad","Sandwich"],["Sauce","Pizza","Quesadilla","Salad"],["Tomato","Pizza","Quesadilla","Salad","Sandwich"]]

Explanation:

"Cheese" appears in dishes "Pizza" and "Quesadilla". "Salad" appears in dishes "Salad", "Sandwich". "Sauce" appears in dishes "Pizza", "Quesadilla", and "Salad". "Tomato" appears in dishes "Pizza", "Quesadilla", "Salad", "Sandwich". All dishes in a group should be sorted alphabetically.

Approach:

The problem can be solved using a hash table/dictionary and string manipulation.

Create an empty dictionary to store all the ingredients.

In the dictionary, the key will be the ingredients, and the value will be the list of dishes containing that ingredient.

Iterate through all the dishes and ingredients:

For each dish, iterate through all the ingredients.

If an ingredient is already present in the dictionary, add the dish to the list of dishes with that ingredient.

If the ingredient is not already present, add the ingredient to the dictionary as a new key and add the dish to the list of dishes with that ingredient.

Iterate through the dictionary and create groups of dishes that have at least 2 identical ingredients.

Sort each group in alphabetical order.

Append each sorted group to the final result list.

Return the final result list.

Code:

def groupDishes(dishes): ingredients_dict = {} for dish in dishes: for i in range(1, len(dish)): ingredient = dish[i] if ingredient in ingredients_dict: ingredients_dict[ingredient].append(dish[0]) else: ingredients_dict[ingredient] = [dish[0]] result = [] for ingredient, dishes in ingredients_dict.items(): if len(dishes) >= 2: result.append([ingredient] + sorted(dishes)) return sorted(result)

Test the code with the provided example inputs:

print(groupDishes([["Salad","Tomato","Cucumber","Salad","Sauce"],["Pizza","Tomato","Sausage","Sauce","Dough"],["Quesadilla","Chicken","Cheese","Sauce"],["Sandwich","Salad","Bread","Tomato","Cheese"]]))

The output of the provided test case is as follows:

[["Cheese","Pizza","Quesadilla"],["Salad","Salad","Sandwich"],["Sauce","Pizza","Quesadilla","Salad"],["Tomato","Pizza","Quesadilla","Salad","Sandwich"]]

Solution Implementation

1