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?- A. 4 95
- B. 3 95
- C. 3 89
- 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
- Problem: The function below should return the integer square root ⌊√x⌋. java static int isqrt(int x) { int lo = 0, hi = x, ans = 0; while…
- Problem: In an array where every element appears twice except one, and pairs sit next to each other, the array is sorted. Find the single…
- Problem: Find a peak element (strictly greater than its neighbours; outside the array counts as −∞). Return its index. python def peak(a)…
- Problem: Return the k-th smallest element of the union of two sorted arrays (k is 1-based) in O(log(m + n)). python def kth(a, b, k): if…
- Problem: Reverse a singly linked list of order IDs. python class Node: def init(self, v, nxt=None): self.v, self.next = v, nxt def…
- Problem: Return the middle node of a linked list (the second middle when the length is even). python class Node: def init(self, v…