Two City Scheduling
Two City Scheduling is a medium arrays & hashing problem solved with the greedy pattern.
The best approach, optimal (greedy by cost difference), runs in O(n log n) time and O(log n) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every split) up.
Problem
A company is flying 2n people to interviews. costs[i] = [aCost_i, bCost_i] is the price of flying person i to city A and to city B.
Exactly n people must go to city A and exactly n to city B. Return the minimum total cost of all the flights.
Examples
Example 1
- Input
costs = [[20, 50], [40, 10], [30, 35], [60, 25]]- Output
85- Why
- Send people 0 and 2 to city A (20 + 30) and people 1 and 3 to city B (10 + 25).
Example 2
- Input
costs = [[5, 8], [9, 4]]- Output
9- Why
- Person 0 flies to A for 5 and person 1 to B for 4.
Example 3
- Input
costs = [[100, 1], [100, 2], [100, 3], [1, 100], [2, 100], [200, 150]]- Output
209- Why
- Three people already prefer B by a wide margin, so person 5 must go to A for 200 even though B would be cheaper for them alone: 1 + 2 + 200 + 1 + 2 + 3 = 209.
Constraints
2 * n == costs.length,2 <= costs.length <= 100, andcosts.lengthis even1 <= aCost_i, bCost_i <= 1000
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every split) | O(C(2n, n)) | O(n) |
| DP over people and A-count | O(n²) | O(n²) |
| Optimal (greedy by cost difference) | O(n log n) | O(log n) |
1Brute force (try every split)
O(C(2n, n))Every way to choose which n people go to A is explored.O(n)Recursion depth is 2n.Decide for each person whether they fly to A or B, but only while the city still has free spots. Explore every valid assignment recursively and keep the minimum cost.
- go(i, a, b) = minimum cost for people i.. with a spots left in A and b in B.
- If i == 2n return 0.
- Try A (if a > 0): costs[i][0] + go(i + 1, a - 1, b), and B (if b > 0): costs[i][1] + go(i + 1, a, b - 1).
- Return the smaller one; start with go(0, n, n).
class Solution {
public int twoCitySchedCost(int[][] costs) {
int n = costs.length / 2;
return go(costs, 0, n, n);
}
private int go(int[][] costs, int i, int a, int b) {
if (i == costs.length) return 0;
int best = Integer.MAX_VALUE;
if (a > 0) best = Math.min(best, costs[i][0] + go(costs, i + 1, a - 1, b));
if (b > 0) best = Math.min(best, costs[i][1] + go(costs, i + 1, a, b - 1));
return best;
}
}class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
total = len(costs)
def go(i: int, a: int, b: int) -> int:
if i == total:
return 0
best = float("inf")
if a > 0:
best = min(best, costs[i][0] + go(i + 1, a - 1, b))
if b > 0:
best = min(best, costs[i][1] + go(i + 1, a, b - 1))
return best
n = total // 2
return go(0, n, n)class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
int n = costs.size() / 2;
return go(costs, 0, n, n);
}
private:
int go(vector<vector<int>>& costs, int i, int a, int b) {
if (i == (int)costs.size()) return 0;
int best = INT_MAX;
if (a > 0) best = min(best, costs[i][0] + go(costs, i + 1, a - 1, b));
if (b > 0) best = min(best, costs[i][1] + go(costs, i + 1, a, b - 1));
return best;
}
};function twoCitySchedCost(costs) {
const total = costs.length;
const go = (i, a, b) => {
if (i === total) return 0;
let best = Infinity;
if (a > 0) best = Math.min(best, costs[i][0] + go(i + 1, a - 1, b));
if (b > 0) best = Math.min(best, costs[i][1] + go(i + 1, a, b - 1));
return best;
};
const n = total / 2;
return go(0, n, n);
}2DP over people and A-count
O(n²)2n people times up to n + 1 values of j.O(n²)The full table has (2n + 1) × (n + 1) cells.The brute force only depends on (i, number sent to A so far), because the B count follows from them. Tabulate dp[i][j] = cheapest cost for the first i people with j of them in A.
- dp[0][0] = 0, everything else infinity.
- For person i (1-based) and j from 0 to min(i, n): dp[i][j] = min(dp[i-1][j-1] + aCost, dp[i-1][j] + bCost), where the B option needs i - j <= n.
- Return dp[2n][n].
class Solution {
public int twoCitySchedCost(int[][] costs) {
int total = costs.length, n = total / 2;
int INF = Integer.MAX_VALUE / 2;
int[][] dp = new int[total + 1][n + 1];
for (int[] row : dp) Arrays.fill(row, INF);
dp[0][0] = 0;
for (int i = 1; i <= total; i++) {
for (int j = 0; j <= Math.min(i, n); j++) {
if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + costs[i - 1][0]);
if (i - j <= n) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + costs[i - 1][1]);
}
}
return dp[total][n];
}
}class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
total = len(costs)
n = total // 2
INF = float("inf")
dp = [[INF] * (n + 1) for _ in range(total + 1)]
dp[0][0] = 0
for i in range(1, total + 1):
a, b = costs[i - 1]
for j in range(min(i, n) + 1):
if j > 0:
dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + a)
if i - j <= n:
dp[i][j] = min(dp[i][j], dp[i - 1][j] + b)
return dp[total][n]class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
int total = costs.size(), n = total / 2;
const int INF = INT_MAX / 2;
vector<vector<int>> dp(total + 1, vector<int>(n + 1, INF));
dp[0][0] = 0;
for (int i = 1; i <= total; i++) {
for (int j = 0; j <= min(i, n); j++) {
if (j > 0) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + costs[i - 1][0]);
if (i - j <= n) dp[i][j] = min(dp[i][j], dp[i - 1][j] + costs[i - 1][1]);
}
}
return dp[total][n];
}
};function twoCitySchedCost(costs) {
const total = costs.length, n = total / 2;
const dp = Array.from({ length: total + 1 }, () => new Array(n + 1).fill(Infinity));
dp[0][0] = 0;
for (let i = 1; i <= total; i++) {
for (let j = 0; j <= Math.min(i, n); j++) {
if (j > 0) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + costs[i - 1][0]);
if (i - j <= n) dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + costs[i - 1][1]);
}
}
return dp[total][n];
}3Optimal (greedy by cost difference)
O(n log n)Sorting the 2n people dominates.O(log n)Only the sort's internal stack.Start from everyone in B. Sending person i to A instead adds aCost - bCost (possibly negative). Exactly n people must switch, so pick the n smallest differences: sort by aCost - bCost, send the first half to A and the rest to B.
- Sort costs by aCost - bCost ascending.
- Add aCost for the first n people and bCost for the last n.
- Return the sum.
class Solution {
public int twoCitySchedCost(int[][] costs) {
Arrays.sort(costs, (p, q) -> Integer.compare(p[0] - p[1], q[0] - q[1]));
int n = costs.length / 2;
int total = 0;
for (int i = 0; i < costs.length; i++) {
total += i < n ? costs[i][0] : costs[i][1];
}
return total;
}
}class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
costs.sort(key=lambda c: c[0] - c[1])
n = len(costs) // 2
return sum(c[0] for c in costs[:n]) + sum(c[1] for c in costs[n:])class Solution {
public:
int twoCitySchedCost(vector<vector<int>>& costs) {
sort(costs.begin(), costs.end(), [](const vector<int>& p, const vector<int>& q) {
return p[0] - p[1] < q[0] - q[1];
});
int n = costs.size() / 2;
int total = 0;
for (int i = 0; i < (int)costs.size(); i++) {
total += i < n ? costs[i][0] : costs[i][1];
}
return total;
}
};function twoCitySchedCost(costs) {
costs.sort((p, q) => (p[0] - p[1]) - (q[0] - q[1]));
const n = costs.length / 2;
let total = 0;
for (let i = 0; i < costs.length; i++) {
total += i < n ? costs[i][0] : costs[i][1];
}
return total;
}Edge cases to test
- Everyone is cheaper in the same city: half of them must still go to the other city
- Ties where A and B cost the same for a person
- Only two people
- Choosing each person's cheaper city independently breaks the n / n split
Hints
Hint 1
Imagine sending everyone to city B first. Moving one person to A changes the total by aCost - bCost.
Hint 2
You must move exactly n people to A. Which n moves are cheapest?
Hint 3
Sort people by aCost - bCost and send the first half to A.
FAQ
What is the best time complexity for Two City Scheduling?
Optimal (greedy by cost difference) runs in O(n log n) time and O(log n) extra space. Sorting the 2n people dominates.
Which pattern does Two City Scheduling use?
It is a arrays & hashing problem that uses the greedy pattern. Other problems with the same pattern: Integer to Roman, Jump Game II, Jump Game.
Is there a brute force solution for Two City Scheduling?
Yes. Brute force (try every split) takes O(C(2n, n)) time and O(n) space. Decide for each person whether they fly to A or B, but only while the city still has free spots.
Which edge cases should I test for Two City Scheduling?
Everyone is cheaper in the same city: half of them must still go to the other city; Ties where A and B cost the same for a person; Only two people; Choosing each person's cheaper city independently breaks the n / n split.