Magicsheet logo

Buy Two Chocolates

Easy
12.5%
Updated 8/1/2025

Asked by 3 Companies

Buy Two Chocolates

What is this problem about?

The Buy Two Chocolates interview question is a greedy optimization problem. You have an array of prices for different chocolates and a starting amount of money. You must buy exactly two chocolates such that the total cost is minimized. If the minimum cost is within your budget, return the remaining money; otherwise, return the original amount of money. This Buy Two Chocolates coding problem is about finding the two smallest values in an array.

Why is this asked in interviews?

Amazon and Meta use this "Easy" level question to check for basic algorithmic efficiency. While you can sort the array, a more optimal solution is to find the two smallest numbers in a single pass. This demonstrates that the candidate understands the difference between O(N log N) and O(N) time complexity.

Algorithmic pattern used

This follows the Array, Sorting, Greedy interview pattern. The greedy choice here is simple: to minimize total cost, you must pick the two cheapest chocolates. This can be done by sorting the array and taking the first two elements, or by maintaining two variables (min1 and min2) during a single iteration.

Example explanation

prices = [3, 2, 3], money = 3

  1. Two smallest prices: 2 and 3.
  2. Total cost: 2 + 3 = 5.
  3. Since 5 > 3 (budget exceeded), we return the original 3. If money = 6:
  4. Total cost: 5.
  5. 5 <= 6. Remaining: 6 - 5 = 1.

Common mistakes candidates make

  • Buying more than two: Misreading the prompt and trying to buy as many as possible within the budget.
  • Sorting unnecessarily: Using prices.sort() when a simple one-pass min-finding logic would be faster (O(N)).
  • Logic for "Remaining Money": Forgetting to return the initial money if the sum exceeds the budget.

Interview preparation tip

When you need to find the k smallest or largest elements in an array where k is small (like 1 or 2), avoid sorting. A linear scan is always more efficient and shows you care about performance.

Similar Questions