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?
  1. A. 10 (-1, 0, 1)
  2. B. 9 (-1, 0, 1)
  3. C. 8 (-1, 0, 1)
  4. 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

Exams that ask this topic