3Sum Smaller
Two Pointer
Problem
Given an array arr
of unsorted numbers and a target sum, count all triplets in it such that arr[i] + arr[j] + arr[k] < target
where i
, j
, and k
are three different indices. Write a function to return the count of such triplets.
Solution
def triplet_with_smaller_sum(arr, target):
count = 0
arr.sort()
for i in range(len(arr)-2):
j = i+1
k = len(arr)-1
while j < k:
sums = arr[i]+arr[j]+arr[k]
if sums < target:
# since arr[k] >= arr[j], therefore, we can
#replace arr[k] by any number between
#left and right to get a sum less than the target sum
count+=k-j
j+=1
else: #sum is too large
k-=1
return count
Last updated
Was this helpful?