Minimize cost & recommend movies
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: This question evaluates algorithmic problem-solving and data-processing competencies, focusing on numeric optimization for making array elements distinct with minimal cost and on traversal and aggregation over a social graph to rank movies by friend and friends-of-friends frequency.
Constraints
- 1 <= n <= 200000
- 0 <= size[i] <= 10^9
- 1 <= cost[i] <= 10^9
- Only increments are allowed
- Output may exceed 32-bit; use 64-bit integer arithmetic
Solution
from typing import List
import heapq
def min_cost_make_distinct(size: List[int], cost: List[int]) -> int:
n = len(size)
if n == 0:
return 0
pairs = sorted(zip(size, cost)) # (s, c)
maxheap = [] # stores (-cost, start_size)
i = 0
pos = pairs[0][0]
total_cost = 0
while i < n or maxheap:
# If heap is empty, jump to next available start size
if not maxheap and i < n and pos < pairs[i][0]:
pos = pairs[i][0]
# Add all items that can start at or before 'pos'
while i < n and pairs[i][0] <= pos:
s, c = pairs[i]
heapq.heappush(maxheap, (-c, s))
i += 1
# Assign current position to the item with the highest cost
if maxheap:
negc, s0 = heapq.heappop(maxheap)
c0 = -negc
total_cost += c0 * (pos - s0)
pos += 1
return total_cost
Explanation
Time complexity: O(n log n). Space complexity: O(n).
Hints
- Sort items by their initial size.
- Sweep positions from left to right; at each integer position, at most one item can be assigned.
- Maintain a max-heap (priority queue) of costs for items whose size is <= current position.
- Greedily assign the current position to the item with the highest per-unit cost to avoid paying that cost in future increments.