Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the three numbers in an array whose sum is closest to a target.
Problem: Find the three numbers in an array whose sum is closest to a target.
def closest3(a, t):
a.sort(); best = a[0] + a[1] + a[2]
for i in range(len(a) - 2):
l, r = i + 1, len(a) - 1
while l < r:
s = a[i] + a[l] + a[r]
if abs(s - t) < abs(best - t): best = s
if s < t: l += 1
elif s > t: r -= 1
else: return s
return best
print(closest3([-1, 2, 1, -4], 1), closest3([0, 0, 0], 1), closest3([1, 1, 1, 0], -100))What is printed?- A. 2 0 1
- B. 0 0 2
- C. 2 0 2
- D. 3 0 2
Correct answer: C. 2 0 2
Sort, fix one element, two-pointer the rest, keeping the closest sum: −1 + 1 + 2 = 2 (distance 1). [0, 0, 0] can only make 0. For target −100 the closest is the smallest possible triple of [0, 1, 1, 1]: 0 + 1 + 1 = 2 (a single 1 is not a triple). O(n²).
More Coding Interview Problems questions
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…
- Problem: Given n ≤ 10⁵ words, find the longest chain where each word is the previous word with exactly one letter inserted (word length ≤…
- Problem: A string of length n = 10⁵; answer q = 10⁵ queries 'are substrings [l1, r1] and [l2, r2] equal?'. Which technique fits?
- Problem: n ≤ 40 items with weights up to 10⁹; count subsets with total weight ≤ W. Why is meet-in-the-middle preferred here?
- Problem: For each element of an array of n = 10⁵, count how many elements to its right are smaller. What is the best complexity?
- Problem: A grid of R × C = 10³ × 10³ heights; find the minimum possible 'maximum step height' along any path from top-left to…