Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Count the UNIQUE triplets (as value sets) that sum to zero, using sort + two pointers with duplicate skipping.

Problem: Count the UNIQUE triplets (as value sets) that sum to zero, using sort + two pointers with duplicate skipping.
def three(a):
    a.sort(); n = len(a); res = 0
    for i in range(n - 2):
        if i and a[i] == a[i-1]: continue
        l, r = i + 1, n - 1
        while l < r:
            s = a[i] + a[l] + a[r]
            if s < 0: l += 1
            elif s > 0: r -= 1
            else:
                res += 1; l += 1; r -= 1
                while l < r and a[l] == a[l-1]: l += 1
    return res
print(three([-2, 0, 1, 1, 2, -1, -4, -1]))
What is printed?
  1. A. 6
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: B. 4

Sorted: [−4, −2, −1, −1, 0, 1, 1, 2]. Unique zero-sum triplets: (−2, 0, 2), (−2, 1, 1), (−1, −1, 2), (−1, 0, 1). Skipping equal values at i and at l prevents (−1, 0, 1) from being counted twice even though there are two −1s and two 1s.

More Coding Interview Problems questions

Exams that ask this topic