Two City Scheduling — LeetCode 1029 Python Solution

MediumGreedyArraySorting
Problem
#1029
Pattern
Greedy
Reading time
2 min

The problem

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.

Example

Input
costs = [[10,20],[30,200],[400,50],[30,20]]
Output
110
Explanation
The first person goes to city A for a cost of 10.

Python solution

Python
class Solution:
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        costs.sort(key=lambda x: x[0] - x[1])
        n = len(costs) >> 1
        return sum(costs[i][0] + costs[i + n][1] for i in range(n))

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1029. Two City Scheduling is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1029. Two City Scheduling?
LeetCode 1029. Two City Scheduling is rated Medium on LeetCode.
What topics does LeetCode 1029. Two City Scheduling cover?
LeetCode 1029. Two City Scheduling is tagged Greedy, Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview