![]() |
VOOZH | about |
Given an array of distinct integers and a sum value. Find count of triplets with sum smaller than given sum value.
Examples:
Input : arr[] = {-2, 0, 1, 3}, sum = 2.
Output : 2
Explanation : Below are triplets with sum less than 2 (-2, 0, 1) and (-2, 0, 3)Input : arr[] = {5, 1, 3, 4, 7}, sum = 12.
Output : 4
Explanation : Below are triplets with sum less than 12 (1, 3, 4), (1, 3, 5), (1, 3, 7) and (1, 4, 5)
Table of Content
Run three loops to consider all triplets one by one. For every triplet, compare the sums and increment count if the triplet sum is smaller than the given sum.
2
Sorting the array first and then, then using the two pointer technique in a loop gives in efficient solution that count triplets in O(n^2)
Step 1: Sort the input array in increasing order.
Step 2: Initialize result as 0.
Step 3: Run a loop from i = 0 to n-2, where each iteration finds all triplets with arr[i] as the first elementa. Initialize the j = i+1 and k = n - 1, as the corner elements of the subarray arr[i+1..n-1].
b. Move j and k toward each other until they meet, i.e., while j < k:
c. If arr[i] + arr[j] + arr[k] >= sum: k-- to reduce the sum.
Else (arr[i] + arr[j] + arr[k] < sum): All elements between j and k also form valid triplets so count them all at once and increment j
Dry run: arr[] = {-2,0, 1, 3}, sum = 2
Final ans = 2
2