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?- A. 290
- B. 260
- C. 250
- 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
- Problem: Delete the fewest characters so that no two distinct letters have the same (non-zero) frequency. python from collections import…
- Problem: Does an array contain indices i < j < k with a[i] < a[j] < a[k]? An O(n), O(1) greedy keeps the smallest 'first' and the smallest…
- Problem: Can a hand of cards be split into groups of exactly w consecutive values? Greedily start groups at the smallest remaining card…
- Problem: Swap at most two digits of a number once to obtain the maximum value. Record the last position of each digit and, scanning left…
- Problem: Flower i blooms on day bloom[i]. A bouquet needs k ADJACENT bloomed flowers, each flower used once. Find the minimum day by which…
- Problem: A number is 'magical' if it is divisible by a or b. Find the n-th magical number by binary search with inclusion–exclusion…