Two City Scheduling (LeetCode 1029): Solution and Explanation
Each of 2n people has a price to fly to city A and a price to fly to city B. Send exactly n people to each city at the lowest total cost.
Intuition
Picture everyone booked to city B first. Switching one person to A changes the bill by a - b, which can be negative (a saving) or positive (an extra charge).
Exactly n people have to switch. To keep the bill as low as possible, switch the n people whose a - b is smallest.
So sort everyone by a - b. The left half flies to A and the right half flies to B. Any swap across that split would replace a smaller difference with a larger one and raise the total.
Approach: Sort by a - b, split in half
- Sort
costsbycosts[i][0] - costs[i][1]in increasing order. - Let
n = len(costs) / 2andtotal = 0. - For the first n people add their A cost to
total. - For the last n people add their B cost to
total, then return it.
Step-by-step example
costs = [[10,20],[30,200],[400,50],[30,20]]
- Differences a - b: -10, -170, 350, 10.
- Sorted by difference: [30,200] (-170), [10,20] (-10), [30,20] (10), [400,50] (350). n = 2.
- First half to A: 30 + 10 = 40.
- Second half to B: 20 + 50 = 70.
- Total 40 + 70 = 110.
Code: Python, Java, C++
1class Solution:
2 def twoCitySchedCost(self, costs: List[List[int]]) -> int:
3 costs.sort(key=lambda c: c[0] - c[1])
4 n = len(costs) // 2
5 total = 0
6 for i in range(2 * n):
7 if i < n:
8 total += costs[i][0]
9 else:
10 total += costs[i][1]
11 return total1class Solution {
2 public int twoCitySchedCost(int[][] costs) {
3 Arrays.sort(costs, (x, y) -> (x[0] - x[1]) - (y[0] - y[1]));
4 int n = costs.length / 2;
5 int total = 0;
6 for (int i = 0; i < 2 * n; i++) {
7 if (i < n) {
8 total += costs[i][0];
9 } else {
10 total += costs[i][1];
11 }
12 }
13 return total;
14 }
15}1class Solution {
2public:
3 int twoCitySchedCost(vector<vector<int>>& costs) {
4 sort(costs.begin(), costs.end(), [](const vector<int>& x, const vector<int>& y) { return x[0] - x[1] < y[0] - y[1]; });
5 int n = costs.size() / 2;
6 int total = 0;
7 for (int i = 0; i < 2 * n; i++) {
8 if (i < n) {
9 total += costs[i][0];
10 } else {
11 total += costs[i][1];
12 }
13 }
14 return total;
15 }
16};Time and space complexity
O(n log n)
Sorting the 2n people dominates. The summing pass is linear.
O(1)
Only a counter besides the in-place sort (which may use O(log n) stack depending on the language).
Other approaches
Dynamic programming (time O(n^2), space O(n^2) or O(n) with a rolling row)
dp[i][j] is the cheapest cost for the first i people with j of them in A. Each person extends either the A count or the B count. Correct but slower and uses more memory.
Quickselect on the difference (time O(n) average, space O(1))
Only the split matters, not the full order, so a selection algorithm can find the n smallest differences in average linear time.
Common mistakes
- Sending each person to their cheaper city. That ignores the rule that each city gets exactly n people.
- Sorting by the A cost alone or by the smaller of the two costs. Only the difference a - b decides who should switch.
- Sorting by |a - b|. The sign matters: a large negative difference means a strong reason to go to A, a large positive one a strong reason to go to B.
- Using a - b subtraction in a comparator with huge values can overflow, though here costs are at most 1000 so it is safe.
Frequently asked questions
Why does sorting by a - b give the optimum?
Any assignment costs sum(b) plus the sum of a - b over the people sent to A. sum(b) is fixed, so the best choice is the n smallest differences, which is the first half after sorting.
How are ties handled?
People with equal a - b change the total by the same amount whichever city they go to, so any tie order gives the same answer.
Does the answer change if everyone prefers the same city?
No. The split still sends the n people who lose the least to the less popular city, which the sort handles the same way.