Triplet counts with sum smaller than given Number
💻 coding

Triplet counts with sum smaller than given Number

1 min read 218 words
1 min read
ShareWhatsAppPost on X
  • 1The problem involves counting triplets in an array whose sum is less than a given value.
  • 2An initial solution uses a cubic time complexity of N^3, iterating through all possible triplet combinations.
  • 3The optimized solution reduces the time complexity to N^2 by sorting the array and using a two-pointer technique.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves counting triplets in an array whose sum is less than a given value."

Triplet counts with sum smaller than given Number

We are given an array of distinct integers and along with it a sum value. We have to find count of triplets with sum that is smaller than the sum value. First we will solve in N^3 Time complexity. then we will be optimizing our current solution for better time complexity.

Example:

Input : arr[] = {6, 2, 4, 5, 8}
 sum = 17.
Output : 4
Explanation : triplets with sum less than 17 are
 (2, 4, 5), (2, 4, 6), (2, 4, 8) and 
 (2, 5, 6)
public class CountTriplets {
	
	private static int calculateTriplets(int[] arr, int sum) {
		//n^3 solution.
		int count=0;
		for(int i=0;i<arr.length-2;i++) {
			for(int j=i+1;j<arr.length-1;j++) {
				for(int k=j+1;k<arr.length;k++) {
					if((arr[i]+arr[j]+arr[k]) < sum)
						count++;
				}
			}
		}
		
		return count;
	}
	
	public static void main(String[] args) {
		int[] arr= new int[] {6, 2, 4, 5, 8};
		int sum = 15;
		System.out.println(calculateTriplets(arr,sum));
	}
}

Now we will optimize the solution for time complexity N^2.

import java.util.Arrays;

public class CountTriplets {
	
	private static int calculateTriplets(int[] arr, int sum) {
		//n^2 solution.
		int count=0;
		Arrays.sort(arr);
		for(int i=0;i<arr.length-2;i++) {
			int j=i+1;
			int k=arr.length-1;
			while(j<k) {
				if((arr[i]+arr[j]+arr[k])<sum) {
					count+=k-j;
					j++;
				}
				else
					k--;
			}
		}
		
		return count;
	}
	
	public static void main(String[] args) {
		int[] arr= new int[] {6, 2, 4, 5, 8};
		int sum = 15;
		System.out.println(calculateTriplets(arr,sum));
	}
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 13 July 2018 · 1 min read · 218 words

Part of AskGif Blog · coding

You might also like