15% off all plans & roadmaps Use code
See plansLeetCode 1029 · Solution & editorial
A company is planning to interview 2n people. Given the array costs where costs[i] = [aCosti, bCosti], the cost of flying the ith person to city a is aCosti, and the cost of flying the ith person to city b is bCosti.
Two City Scheduling is a Greedy Patterns problem, in the Sorting Based subpattern. The pattern covers interval scheduling, jump games, stock trading, and task scheduling
Solve greedy problems that require sorting as preprocessing step for optimal solutions.
The reference solution runs in O(n) time and O(1) space.
Two City Scheduling has been reported in interviews at Bloomberg.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Two City Scheduling is a Greedy Patterns problem, in the Sorting Based subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.