← Two Sigma Interview Insights
My first instinct was brute force and I basically said that out loud before catching myself.
First, clarify the problem: we need to choose exactly n workers for task A and the remaining n for task B, minimizing the sum of their respective costs. A greedy approach works: sort workers by the difference (costA - costB), assign the first n to task A and the rest to task B. Prove optimality via an exchange argument.
Pro tip: Mention that this is a classic scheduling problem solvable in O(n log n) time, and emphasize that the greedy choice is optimal because any swap that moves a worker from B to A and another from A to B cannot reduce the total cost when the list is sorted by the difference.
Restate the problem: given 2n workers with costs (a_i, b_i), assign exactly n to task A and n to task B to minimize total cost. Confirm that each worker must be assigned to exactly one task.
Compute the difference d_i = a_i - b_i for each worker. Sort workers by d_i in ascending order. Assign the first n workers to task A and the remaining n to task B.
Use an exchange argument: if there is an optimal assignment that differs, swapping a worker assigned to B with one assigned to A (where the B worker has a smaller d) does not increase the total cost. Thus the sorted greedy assignment is optimal.
Sorting takes O(n log n) time, and computing the total cost takes O(n) time. Space complexity is O(n) for storing the differences or O(1) extra if sorting in place.
Consider cases where costs are equal, or when n=1. Also mention that the same approach works if we need to assign exactly k workers to A and 2n-k to B, by sorting and picking the k smallest differences.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.