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?- A. 1
- B. 5
- C. 2
- 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
- Problem: For each element, the nearest smaller value to its LEFT (−1 if none), with a monotonic stack. python def leftsmaller(a): st, out…
- Problem: Report the first negative number in every window of size k (0 if none), using a queue of negative indices. python from…
- Problem: Reorder a linked list L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place (find middle, reverse second half, merge). python…
- Problem: From a sorted linked list, delete EVERY value that appears more than once (keep only distinct values). python class N: def…
- Problem: Sum all LEFT leaves of a binary tree (leaves that are the left child of their parent). python class T: def init(s, v): s.v, s.l…
- Problem: List every root-to-leaf path whose values sum to the target. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…