Two City Scheduling
Problem Statement
A company must fly 2n people to two cities, A and B. Person i costs costs[i][0] to fly to city A and costs[i][1] to fly to city B.
Send exactly n people to each city. Return the smallest total cost.
costs: a list of [costA, costB] pairs, one per person. Its length is 2n.
One integer: the smallest total cost with exactly n people in each city.
Persons 0 and 1 go to A (10 + 30). Persons 2 and 3 go to B (50 + 20). Total 110.
Persons 0, 3 and 5 go to A (259 + 184 + 577 = 1020). Persons 1, 2 and 4 go to B (54 + 667 + 118 = 839). Total 1859.
Four people go to each city, and the cheapest split costs 3086.
- • The number of people is even: `costs.length = 2n`.
- • 2 ≤ costs.length ≤ 100
- • 1 ≤ costA, costB ≤ 1000
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try every way to choose which n people go to A (C(2n, n) ways)
dp[i][a] = cheapest cost for the first i people with a of them sent to A
Sort by costA − costB; the n people with the smallest difference go to A
Go through the people one by one. Each person goes to A or B, but only while that city still has an open seat. Try both choices at every step and keep the cheapest full plan. The number of full plans is C(2n, n), the ways to pick which n people go to A.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Greedy translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.