Two City Scheduling

Medium Arrays & Hashing Greedy Original on LeetCode

Reported atSwiggy

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, and costs.length is even
  • 1 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
Brute force (try every split)O(C(2n, n))O(n)
DP over people and A-countO(n²)O(n²)
Optimal (greedy by cost difference)O(n log n)O(log n)

1Brute force (try every split)

TimeO(C(2n, n))Every way to choose which n people go to A is explored.
SpaceO(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.

  1. go(i, a, b) = minimum cost for people i.. with a spots left in A and b in B.
  2. If i == 2n return 0.
  3. 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).
  4. 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;
    }
}

2DP over people and A-count

TimeO(n²)2n people times up to n + 1 values of j.
SpaceO(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.

  1. dp[0][0] = 0, everything else infinity.
  2. 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.
  3. 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];
    }
}

3Optimal (greedy by cost difference)

TimeO(n log n)Sorting the 2n people dominates.
SpaceO(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.

  1. Sort costs by aCost - bCost ascending.
  2. Add aCost for the first n people and bCost for the last n.
  3. 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;
    }
}

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.