We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Burgers with No Waste of Ingredients

Difficulty: Medium


Problem Description

Given two integers tomatoSlices and cheeseSlices, determine the number of Jumbo and Small burgers that can be made such that there are no remaining ingredients. A Jumbo Burger requires 4 tomato slices and 1 cheese slice, while a Small Burger requires 2 tomato slices and 1 cheese slice. Return the count of Jumbo and Small burgers in the format [total_jumbo, total_small]. If it is not possible to use all ingredients, return an empty list.


Key Insights

  • Each Jumbo Burger uses 4 tomato slices and 1 cheese slice.
  • Each Small Burger uses 2 tomato slices and 1 cheese slice.
  • The total number of cheese slices must equal the total number of burgers made (both Jumbo and Small).
  • The total number of tomato slices must equal 4 * total_jumbo + 2 * total_small.
  • A valid solution exists only if the number of cheese slices is less than or equal to the total number of burgers and the remaining tomato slices can be perfectly divided by the number of burgers.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

To solve this problem, we can set up a system of equations based on the constraints provided by the burger definitions. Let j be the number of Jumbo Burgers and s be the number of Small Burgers. We then have:

  1. j + s = cheeseSlices (total burgers)
  2. 4j + 2s = tomatoSlices (total tomato slices)

From the first equation, we can express s in terms of j:
s = cheeseSlices - j

Substituting this into the second equation gives us:
4j + 2(cheeseSlices - j) = tomatoSlices
This simplifies to:
2j + 2 * cheeseSlices = tomatoSlices

Rearranging yields:
2j = tomatoSlices - 2 * cheeseSlices
j = (tomatoSlices - 2 * cheeseSlices) / 2

To ensure j is a non-negative integer, both tomatoSlices - 2 * cheeseSlices must be non-negative and even. Using j, we can find s:

s = cheeseSlices - j

If both j and s are non-negative, we return [j, s]. Otherwise, we return an empty list.


Code Solutions

def numOfBurgers(tomatoSlices: int, cheeseSlices: int):
    j = (tomatoSlices - 2 * cheeseSlices) // 2  # Calculate Jumbo burgers
    s = cheeseSlices - j  # Calculate Small burgers
    
    # Check if the number of burgers is valid
    if j < 0 or s < 0 or (tomatoSlices - 2 * cheeseSlices) % 2 != 0:
        return []
    
    return [j, s]  # Return the total number of Jumbo and Small burgers
← Back to All Questions