Magicsheet logo

Collecting Chocolates

Medium
72.9%
Updated 6/1/2025

Asked by 2 Companies

Collecting Chocolates

What is this problem about?

In the Collecting Chocolates interview question, you are given an array of chocolate costs where each index represents a different type. You can perform two actions:

  1. Collect chocolates of any types at their current costs.
  2. Rotate the array (at a fixed cost x) so that the chocolate at index i now has the cost of the chocolate previously at (i-1) % n. You must find the minimum total cost to have collected all types of chocolates at least once.

Why is this asked in interviews?

Amazon asks this Array interview pattern to test optimization and search space reduction. It seems like it could be a complex dynamic programming problem, but it can be solved by realizing that the number of possible rotations is limited (at most n-1 rotations). It tests if you can identify that a brute-force check of all rotation counts is actually efficient enough.

Algorithmic pattern used

The pattern is Brute Force on Rotations combined with Dynamic Minimum Tracking:

  • There are only n possible rotation counts (from 0 to n-1).
  • For each rotation count k, the cost of chocolate i is the minimum cost it has seen across all rotations from 0 to k.
  • Total cost for k rotations = (k * x) + sum(min_cost_for_each_type).
  • The answer is the minimum total cost across all k.

Example explanation

Costs: [20, 1, 15], Rotation cost x: 5

  1. k=0 rotations: Total = 0 + (20 + 1 + 15) = 36.
  2. k=1 rotations:
    • Type 0 can cost 20 or 15 (after 1 rotation). Min = 15.
    • Type 1 can cost 1 or 20. Min = 1.
    • Type 2 can cost 15 or 1. Min = 1.
    • Total = 5 + (15 + 1 + 1) = 22.
  3. k=2 rotations:
    • Type 0 min: min(20, 15, 1) = 1.
    • Type 1 min: min(1, 20, 15) = 1.
    • Type 2 min: min(15, 1, 20) = 1.
    • Total = 10 + (1 + 1 + 1) = 13. Result: 13.

Common mistakes candidates make

  • Over-rotation: Thinking you might need more than n-1 rotations.
  • Greedy rotation: Trying to decide whether to rotate based on immediate cost gain instead of checking all possible rotation counts.
  • Complexity: Not using an auxiliary array to keep track of the minimum cost for each type as you increment rotations, leading to an O(N^3) solution instead of O(N^2).

Interview preparation tip

Always check the constraints. If n is small (e.g., 1000 or 2000), an O(N^2) solution is perfectly acceptable and often expected over a complex DP approach.

Similar Questions