Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers.

Problem: Count unique quadruplets (as value multisets) summing to target with sort + two nested loops + two pointers.
def four(a, t):
    a.sort(); n = len(a); res = 0
    for i in range(n):
        if i and a[i] == a[i-1]: continue
        for j in range(i + 1, n):
            if j > i + 1 and a[j] == a[j-1]: continue
            l, r = j + 1, n - 1
            while l < r:
                s = a[i] + a[j] + a[l] + a[r]
                if s < t: l += 1
                elif s > t: r -= 1
                else:
                    res += 1; l += 1
                    while l < r and a[l] == a[l-1]: l += 1
    return res
print(four([2, 2, 2, 2, 2, 1, 0, -1, -2, 3], 8))
What is printed?
  1. A. 1
  2. B. 5
  3. C. 2
  4. D. 3

Correct answer: C. 2

Duplicates are skipped at every level, so each value multiset is counted once. The quadruplets summing to 8 are {2, 2, 2, 2} and {3, 2, 2, 1}: 2, matching brute force even though there are five 2s.

More Coding Interview Problems questions

Exams that ask this topic