Data Structures & AlgorithmsVery hardProduct company OA
Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary search on the answer d, counting pairs with difference ≤ d by two pointers.
Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary search on the answer d, counting pairs with difference ≤ d by two pointers.
def kth_pair_dist(a, k):
a = sorted(a)
def pairs_le(d):
c = j = 0
for i in range(len(a)):
while a[i] - a[j] > d: j += 1
c += i - j
return c
lo, hi = 0, a[-1] - a[0]
while lo < hi:
mid = (lo + hi) // 2
if pairs_le(mid) >= k: hi = mid
else: lo = mid + 1
return lo
a = [9, 1, 6, 3, 14, 6]
print(kth_pair_dist(a, 1), kth_pair_dist(a, 5), kth_pair_dist(a, 15))What is printed?- A. 0 2 13
- B. 1 3 13
- C. 0 3 13
- D. 0 3 8
Correct answer: C. 0 3 13
pairs_le(d) is non-decreasing in d, so the smallest d with pairs_le(d) ≥ k is the k-th smallest distance – and it is always an actual distance. Sorted: [1, 3, 6, 6, 9, 14]. d = 0 already has one pair (6, 6). Distances sorted: 0, 2, 3, 3, 3, … so the 5th is 3. With 15 pairs the 15th is the maximum, 14 − 1 = 13. O(n log n + n log(range)).
More Coding Interview Problems questions
- Problem: Tasks of given lengths must be packed into work sessions of at most T = 8 hours; a task cannot be split. Exact bitmask DP (state…
- Problem: Paint a 3 × n wall: each cell gets one of 3 colours and side-adjacent cells must differ. Count valid colourings by DP over row…
- Problem: Each event (start day, end day) can be attended on any ONE day in its range, and you can attend at most one event per day…
- Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph…
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…