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?- A. 7
- B. 9
- C. 8
- 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
- A divide-and-conquer routine satisfies T(n) = 4T(n/2) + n² log n. What is its running time?
- Edge case: A helper collects items into a list using a default argument. python def collect(x, out=[]): out.append(x) return out a =…
- Problem: n servers are joined by cables one at a time. Count the connected groups at the end and how many cables were redundant (joined…
- Problem: Task IDs 0..5 with dependencies u → v (u before v). The scheduler always runs the SMALLEST available ID next. python import heapq…
- Problem: Dijkstra with a lazy binary heap: outdated heap entries are skipped when popped. Report the distance to node 4 and how many stale…
- Problem: Longest increasing subsequence in O(n log n) with a 'tails' array (tails[i] = smallest possible tail of an increasing subsequence…