Cook Off - codepath/compsci_guides GitHub Wiki

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q:
    • What is the desired outcome?
      • To find the maximum number of copies of target_meal that can be created using the given ingredients.
  • Q:
    • What input is provided?
      • Two strings, ingredients and target_meal.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Count the frequency of each character in ingredients and target_meal, then determine how many times target_meal can be formed by dividing the counts.

1) Count the frequency of each character in `ingredients` and `target_meal`.
2) Initialize `max_copies` to infinity.
3) For each character in `target_meal`, check if it is present in `ingredients`.
   - If not, return 0.
   - Otherwise, update `max_copies` with the minimum value of the integer division of the counts.
4) Return `max_copies`.

⚠️ Common Mistakes

  • Not correctly handling the case where a character in target_meal is missing from ingredients.

I-mplement

def max_attempts(ingredients, target_meal):
    # Step 1: Manually count the frequency of each character in ingredients
    ingredients_count = {}
    for char in ingredients:
        if char in ingredients_count:
            ingredients_count[char] += 1
        else:
            ingredients_count[char] = 1
    
    # Step 2: Manually count the frequency of each character in target_meal
    target_meal_count = {}
    for char in target_meal:
        if char in target_meal_count:
            target_meal_count[char] += 1
        else:
            target_meal_count[char] = 1
    
    max_copies = float('inf')
    
    # Step 3: Calculate the maximum number of times the target meal can be made
    for char in target_meal_count:
        if char not in ingredients_count:
            return 0
        max_copies = min(max_copies, ingredients_count[char] // target_meal_count[char])
    
    return max_copies