Bird
Raised Fist0

Identify the subtle bug in the following code snippet for Two City Scheduling: def twoCitySchedCost(costs): costs.sort(key=lambda x: abs(x[0] - x[1])) n = len(costs) // 2 total = 0 for i in range(n): total += costs[i][0] for i in range(n, 2*n): total += costs[i][1] return total

medium🐞 Bug Identification Q7 of Q15
Greedy Algorithms - Two City Scheduling
Identify the subtle bug in the following code snippet for Two City Scheduling: def twoCitySchedCost(costs): costs.sort(key=lambda x: abs(x[0] - x[1])) n = len(costs) // 2 total = 0 for i in range(n): total += costs[i][0] for i in range(n, 2*n): total += costs[i][1] return total
ASorting by absolute difference instead of signed difference causes suboptimal assignments
BOff-by-one error in loop ranges causing index out of bounds
CAssigning more than n people to city A violates constraints
DNot handling equal cost differences leads to runtime error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze sorting key

    Sorting by absolute difference loses sign information, which is critical to decide city assignment.
  2. Step 2: Consequence of bug

    Incorrect sorting order leads to suboptimal total cost, violating problem goal.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Signed difference sorting is essential for correct greedy assignment [OK]
Quick Trick: Sort by signed difference, not absolute difference [OK]
Common Mistakes:
MISTAKES
  • Using abs() in sorting key
  • Ignoring sign of cost difference
  • Assuming absolute difference works
Trap Explanation:
PITFALL
  • Candidates think absolute difference is equivalent, but it breaks greedy logic.
Interviewer Note:
CONTEXT
  • Tests ability to spot subtle bug in sorting key affecting correctness
Master "Two City Scheduling" in Greedy Algorithms

3 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Greedy Algorithms Quizzes