Imagine you are organizing a conference and need to send exactly half of the attendees to city A and the other half to city B, minimizing total travel costs.
There are 2n people and two cities: city A and city B. The cost of sending the i-th person to city A is costs[i][0], and to city B is costs[i][1]. You need to send exactly n people to city A and n people to city B. Find the minimum total cost to do so.
2n == costs.length1 ≤ n ≤ 10^5costs[i].length == 21 ≤ costs[i][j] ≤ 10^4
Edge cases: All costs to city A are cheaper → output sum of first n costs to city AAll costs to city B are cheaper → output sum of first n costs to city BCosts are equal for both cities for all people → output sum of costs for any n assigned to each city
def twoCitySchedCost(costs: list[list[int]]) -> int:public int twoCitySchedCost(int[][] costs)int twoCitySchedCost(vector<vector<int>>& costs)function twoCitySchedCost(costs)
def twoCitySchedCost(costs):
# Write your solution here
pass
class Solution {
public int twoCitySchedCost(int[][] costs) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int twoCitySchedCost(vector<vector<int>>& costs) {
// Write your solution here
return 0;
}
function twoCitySchedCost(costs) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: Sum of cheapest city per person without balancingAssigning each person to their individually cheapest city ignoring the constraint of exactly n people per city.✅ Sort people by cost difference and assign first n to city A and rest to city B.
Wrong: Crash or error on empty inputNo check for empty costs array before processing.✅ Add base case: if costs is empty, return 0 immediately.
Wrong: Incorrect total cost due to off-by-one in assignment countNot enforcing exactly n assignments per city, leading to unbalanced assignments.✅ Track count of assignments and ensure exactly n people assigned to each city.
Wrong: Wrong output due to incorrect sorting orderSorting by cost difference in descending order or by wrong key.✅ Sort ascending by (costA - costB) to prioritize people cheaper to city A.
Wrong: TLE on large inputsUsing brute force or exponential approach instead of sorting and greedy.✅ Implement O(n log n) sorting and greedy assignment to meet time constraints.