Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by sorting on costA − costB.

Problem: A company sends 2n candidates to two interview centres, n to each; costs[i] = (cost at A, cost at B). Minimise the total cost by sorting on costA − costB.
def two_city(costs):
    costs = sorted(costs, key=lambda c: c[0] - c[1])
    n = len(costs) // 2
    return sum(c[0] for c in costs[:n]) + sum(c[1] for c in costs[n:])
print(two_city([(30, 200), (400, 50), (100, 120), (60, 70)]))
What is printed?
  1. A. 290
  2. B. 260
  3. C. 250
  4. D. 240

Correct answer: C. 250

Send everyone to B, then switching person i to A changes the cost by costA − costB; pick the n most negative differences. Differences: −170, 350, −20, −10 → A gets (30, 200) and (100, 120): 30 + 100; B gets (60, 70) and (400, 50): 70 + 50 → 250. Taking each person's cheaper centre ignores the n-each rule (it would send three people to A). O(n log n).

More Coding Interview Problems questions

Exams that ask this topic