Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return all unique triplets that sum to zero.
Problem: Return all unique triplets that sum to zero.
def three_sum(a):
a.sort(); res = []
for i in range(len(a) - 2):
if i and a[i] == a[i - 1]: continue
l, r = i + 1, len(a) - 1
while l < r:
s = a[i] + a[l] + a[r]
if s < 0: l += 1
elif s > 0: r -= 1
else:
res.append((a[i], a[l], a[r])); l += 1; r -= 1
while l < r and a[l] == a[l - 1]: l += 1
return res
r = three_sum([-1, 0, 1, 2, -1, -4, -2, -3, 3, 0, 4])
print(len(r), r[-1])What is printed?- A. 10 (-1, 0, 1)
- B. 9 (-1, 0, 1)
- C. 8 (-1, 0, 1)
- D. 9 (0, 0, 0)
Correct answer: B. 9 (-1, 0, 1)
Sort, fix a[i], two-pointer for −a[i], skipping equal values for i and for l to avoid duplicate triplets. The nine unique triplets are (−4,0,4), (−4,1,3), (−3,−1,4), (−3,0,3), (−3,1,2), (−2,−1,3), (−2,0,2), (−1,−1,2), (−1,0,1). (0,0,0) needs three zeros but only two exist. Without the skips, (−1,0,1) would appear twice. O(n²).
More Coding Interview Problems questions
- 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…
- Problem: Count distinct values in every window of size k over n = 10⁶ values. What is the optimal complexity?