#1029

Two City Scheduling

Medium
ArrayGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

In the optimal approach, we leverage sorting based on the difference between costs for cities A and B. This helps us prioritize which people should be sent to which city based on the cost difference, ensuring we minimize the total cost while maintaining the balance of n people in each city.

⚙️

Algorithm

4 steps
  1. 1Step 1: Calculate the difference between the costs for each person to go to city A and city B.
  2. 2Step 2: Sort the array based on these differences.
  3. 3Step 3: Select the first n people to go to city A and the remaining n people to go to city B.
  4. 4Step 4: Sum the costs for the selected people to get the minimum total cost.
solution.py5 lines
1# Full working Python code
2def twoCitySchedCost(costs):
3    costs.sort(key=lambda x: x[0] - x[1])
4    n = len(costs) // 2
5    return sum(costs[i][0] for i in range(n)) + sum(costs[i][1] for i in range(n, 2 * n))

Complexity note: The sorting step dominates the time complexity, making it O(n log n). The subsequent summation is O(n), which is efficient.

  • 1Sorting based on cost differences helps prioritize cheaper options.
  • 2Balancing the number of people in each city is crucial for minimizing costs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.