Two City Scheduling solution explained
Two City Scheduling is solved by sorting people on the difference between their two costs, cost to A minus cost to B, then sending the first half of that sorted list to city A and the rest to city B. The reasoning is an exchange argument: if everyone starts in B, moving a person to A changes the bill by exactly that difference, so you move the n people with the smallest differences. It runs in O(n log n) time.
By Evin JohnPublished 8 min read
The problem in plain words
A company is running a two-site workshop and has invited an even number of guests. For each guest the travel team has two quotes: the fare to the first site and the fare to the second. Each site must host exactly half of the guests. Choose who goes where so the total spent on fares is as small as possible, and return that total.
| Fares as [to A, to B] | Cheapest total | Who goes to A |
|---|---|---|
| [10, 40], [30, 20], [50, 55], [25, 70] | 110 | The first and the fourth guest |
| [5, 9], [8, 3] | 8 | The first guest; the second goes to B |
| [7, 7], [7, 7] | 14 | Either one, the split does not matter |
| [20, 10], [15, 35], [40, 10], [30, 32], [12, 50], [60, 45] | 122 | The second, fourth and fifth guests |
A few quick questions help: is the number of people always even (normally yes), can fares be equal or zero, and do you need the assignment or only the total? The usual version asks only for the total, but returning the split is a one-line change, so offer it.
Tempting rules that fail
Sending people to whichever city is cheaper for them breaks the half-and-half rule as soon as most people prefer the same city. Sorting by the A fare alone and sending the cheapest n to A ignores how expensive B is for them. Take fares [1, 100], [2, 3], [50, 200], [60, 61]: the two cheapest A fares belong to the first two guests, giving 1 + 2 + 200 + 61 = 264, while sending the first and third guests to A costs only 1 + 50 + 3 + 61 = 115. What matters is not either fare on its own but how much you lose by choosing one city over the other. That gap is the quantity to sort on.
The exchange argument
Start from an imaginary plan where every guest flies to B. Its cost is the sum of all B fares. Now you must move exactly n guests to A. Moving guest i changes the total by a_i - b_i, which may be negative (A is cheaper) or positive (A is pricier). These changes are independent of each other, so the cheapest plan moves the n guests whose a_i - b_i values are smallest. Sorting by that difference and taking the first half does exactly this.
If an interviewer asks for proof, this paragraph is it. You can also phrase it as a swap: if some guest x in A has a larger difference than some guest y in B, swapping them changes the total by (a_y - b_y) - (a_x - b_x), which is not positive, so a sorted split is never beaten.
Slow approach: DP on how many went to A
Before seeing the exchange argument, a DP is the safe path. Process guests one at a time and track cheapest[a], the lowest cost so far with a guests sent to A. Each guest either goes to A, if A still has room, or to B, if B still has room. After all 2n guests, cheapest[n] is the answer. It takes O(n²) time and O(n) space, which is fine for a few hundred people and makes no clever assumptions.
def two_city_slow(costs):
n = len(costs) // 2
INF = float("inf")
cheapest = [0] + [INF] * n # cheapest[a]: lowest cost with a guests in A
for i, (fare_a, fare_b) in enumerate(costs):
nxt = [INF] * (n + 1)
for a in range(min(i, n) + 1):
if cheapest[a] == INF:
continue
if a < n:
nxt[a + 1] = min(nxt[a + 1], cheapest[a] + fare_a)
if i - a < n:
nxt[a] = min(nxt[a], cheapest[a] + fare_b)
cheapest = nxt
return cheapest[n]Main approach: sort by the difference
Sort the pairs by fare_a - fare_b in ascending order. The first half of the sorted list are the guests for whom A is the best deal relative to B, so they go to A. Everyone else goes to B. Add up the matching fares and return the sum.
def two_city(costs):
order = sorted(costs, key=lambda c: c[0] - c[1])
half = len(order) // 2
return sum(a for a, _ in order[:half]) + sum(b for _, b in order[half:])function twoCity(costs) {
const order = [...costs].sort((x, y) => (x[0] - x[1]) - (y[0] - y[1]));
const half = order.length / 2;
let total = 0;
order.forEach(([a, b], i) => {
total += i < half ? a : b;
});
return total;
}A neat variant computes the sum of every B fare first, then adds the n smallest differences. It returns the same number and makes the exchange argument visible in the code itself. If an interviewer pushes on speed, the n smallest differences can be found with quickselect in O(n) average time instead of a full sort.
Working the first example by hand
Fares are [10, 40], [30, 20], [50, 55], [25, 70]. Their differences are -30, 10, -5 and -45. Sorted, the order is guest four (-45), guest one (-30), guest three (-5), guest two (10). The first two go to A, paying 25 and 10. The last two go to B, paying 55 and 20. The total is 110. With the 'all to B' framing: B fares sum to 185, and the two smallest differences, -45 and -30, bring it down to 110.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Try every way to choose n guests for A | O(C(2n, n) · n) | O(n) |
| DP over guests and A count | O(n²) | O(n) |
| Sort by difference | O(n log n) | O(n); sorting in place avoids the copy |
| Quickselect on differences | O(n) average | O(n) |
Edge cases to test
- Two guests only: the cheaper of the two possible splits.
- Everyone prefers A by a wide margin: half of them must still go to B, and the sort picks those who lose least.
- Ties in the difference: any order among tied guests gives the same total, so the sort's tie-breaking does not matter.
- Equal fares for a guest: a difference of zero, which sorts into the middle naturally.
- Zero fares: perfectly valid and handled like any other number.
Mistakes that cost points
- Sorting by fare_a alone, or by the absolute difference, which loses the sign that says which city a guest prefers.
- Sending each guest to their cheaper city and then trying to patch the imbalance by hand.
- Sorting in descending order and then sending the first half to A, which picks the worst guests for A.
- Sorting the caller's list in place without asking whether that is allowed.
- In JavaScript, calling sort() without a comparator, which compares the arrays as strings.
- Claiming the greedy is obvious without the 'everyone starts in B' argument. The proof is short, so give it.
How to explain it out loud
Fictional example
- Candidate
- Imagine everyone flies to B first. Moving a person to A then costs a minus b extra, and those changes do not interact.
- Candidate
- So I want the n people with the smallest a minus b in city A. I sort by that difference, send the first half to A and the rest to B, and add up the fares.
- Candidate
- That is O(n log n) for the sort. If you want, I can swap the sort for quickselect to get linear time on average.
Other problems in this set
Boats to Save People is another sort-then-pair greedy, this time with two pointers moving toward each other. If you want to see a greedy built on coverage instead of cost, revisit Minimum Number of Taps to Open to Water a Garden. The algorithm interview questions page has more on proving greedy choices.
Practice it with Natively
Greedy problems reward a clear proof, and that is easy to skip under time pressure. In a practice session, Natively can read the problem from a screenshot and offer an approach plus a short justification, which you can compare with your own after trying it yourself. Its transcript of your mock interview, kept on your computer, lets you check whether you actually said the exchange argument out loud. Read about an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Two City Scheduling?
Sort the people by cost to A minus cost to B. Send the first half of the sorted list to city A and the second half to city B, then add up the matching costs. It runs in O(n log n) time.
Why does sorting by the cost difference work?
Imagine everyone goes to B first. Moving one person to A changes the total by exactly their A cost minus B cost, and those changes are independent, so moving the n people with the smallest differences gives the cheapest plan.
Can Two City Scheduling be solved with dynamic programming?
Yes. Track the cheapest cost for each count of people sent to A while processing people one by one. It is correct in O(n²) time and is a safe fallback if you do not see the greedy proof.
Can it be faster than O(n log n)?
Only the n smallest differences matter, so a selection algorithm such as quickselect finds them in O(n) average time without a full sort.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
