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?- A. 6
- B. 4
- C. 3
- 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
- Problem: Count subarrays whose sum is exactly k when values may be negative (prefix sums + hash map of prefix counts). python def count(a…
- Search for a value in a sorted array that was rotated and MAY CONTAIN DUPLICATES (e.g. [1, 1, 1, 1, 0, 1, 1]). What is the worst-case time…
- Problem: Return the index of ANY peak element (strictly greater than its neighbours; a[−1] = a[n] = −∞) in O(log n). python def peak(a)…
- Problem: In an n × n matrix whose rows and columns are both sorted, find the k-th smallest value by binary searching on the VALUE and…
- Problem: Reverse the nodes of a singly linked list from position m to n (1-based) in one pass. python class N: def init(s, v, nx=None)…
- Problem: Group a linked list's nodes at odd POSITIONS first, then the nodes at even positions, keeping relative order. python class N: def…