Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible.

Problem: Place c routers at given positions on a road so the minimum distance between any two routers is as large as possible.
def can(pos, c, d):
    cnt, last = 1, pos[0]
    for p in pos[1:]:
        if p - last >= d:
            cnt += 1; last = p
    return cnt >= c
def best(pos, c):
    pos.sort()
    lo, hi = 1, pos[-1] - pos[0]
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if can(pos, c, mid): lo = mid
        else: hi = mid - 1
    return lo
print(best([1, 2, 8, 4, 9], 3), best([5, 17, 100, 11], 2))
What is printed?
  1. A. 4 95
  2. B. 3 95
  3. C. 3 89
  4. D. 2 95

Correct answer: B. 3 95

Maximise the minimum gap: greedy placement from the left tells whether gap d is achievable, and achievability is monotonic. Sorted [1, 2, 4, 8, 9]: gap 3 places 1, 4, 8; gap 4 places only 1, 8 (and 9 is too close). With 2 routers use the two ends: 100 − 5 = 95. The upper mid (lo + hi + 1) // 2 is needed because lo = mid, otherwise the loop never ends.

More Coding Interview Problems questions

Exams that ask this topic