Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as possible. The code binary-searches on the answer.

Problem: Install c routers at some of the given highway mile-markers so that the smallest distance between any two routers is as LARGE as possible. The code binary-searches on the answer.
def ok(p, c, d):
    cnt, last = 1, p[0]
    for x in p[1:]:
        if x - last >= d:
            cnt, last = cnt + 1, x
    return cnt >= c
def best(p, c):
    p.sort(); lo, hi = 1, p[-1] - p[0]
    while lo < hi:
        mid = (lo + hi + 1) // 2
        if ok(p, c, mid): lo = mid
        else: hi = mid - 1
    return lo
print(best([2, 13, 7, 21, 30, 16], 4))
What is printed?
  1. A. 7
  2. B. 9
  3. C. 8
  4. D. 11

Correct answer: C. 8

After sorting [2, 7, 13, 16, 21, 30], gap 8 still fits four routers (2, 13, 21, 30) but gap 9 fits only three (2, 13, 30), so the answer is 8. The upper mid (lo + hi + 1) // 2 prevents an infinite loop when lo = mid.

More Coding Interview Problems questions

Exams that ask this topic