← Questions
Cheapest way to make product sizes distinct
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's technical phone screen, last asked Jul 2025. It tests greedy, heap and sorting.
You have n products. Product i has size size[i], and raising that size by one unit costs cost[i]. Sizes can only go up, never down. Return the least total cost that leaves every product with a different size.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
min_cost_distinct(size: list[int], cost: list[int]) -> int— the two lists have the same length; returns the minimum total cost.
Example
size = [3, 7, 9, 7, 8], cost = [5, 2, 5, 7, 5] -> 6
# raise the cost-2 product from 7 to 10: sizes 3, 10, 9, 7, 8
size = [1, 1, 1], cost = [1, 2, 3] -> 4
# the cost-3 product stays at 1, cost-2 moves to 2 (pays 2), cost-1 to 3 (pays 2)
Constraints
1 <= n <= 200,000-
0 <= size[i] <= 10^9,1 <= cost[i] <= 10^9 - The answer can exceed 32 bits.
Clarifying questions
- Can a size only increase, and by whole units?
- Is any final size allowed, with no upper limit?
- Can the total overflow a 32-bit integer?
- Do equal sizes with equal costs need any particular handling?
What a strong answer covers
- Why a greedy works: when several products compete for the same size, the one with the highest unit cost should keep it and the cheaper ones move up.
- A sweep over sizes in sorted order with a max-heap of the unit costs of products waiting for a slot. At each size, the most expensive waiting product takes it; every product still waiting pays its unit cost once more.
- Jumping the sweep to the next product's size when the heap is empty, so the run time does not depend on how large the sizes are.
- A running sum of the waiting costs so each step is O(log n); O(n log n) overall.
- 64-bit totals, and tests: all sizes equal, already distinct, one product.
Follow-ups
- Sizes may also go down, at a different per-unit cost. What changes?
- Every final size must stay at or below a cap
M. When is it impossible? - Return the final sizes, not only the cost.
Where it's asked
- Amazon · Technical phone screen · Last asked Jul 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
