Given an unsorted array of positive integers, find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any of the two values (or sides) must be greater than the third value (or third side).
Examples:
Input: arr= {4, 6, 3, 7} Output: 3 Explanation: There are three triangles possible {3, 4, 6}, {4, 6, 7} and {3, 6, 7}. Note that {3, 4, 7} is not a possible triangle. Input: arr= {10, 21, 22, 100, 101, 200, 300}. Output: 6 Explanation: There can be 6 possible triangles: {10, 21, 22}, {21, 100, 101}, {22, 100, 101}, {10, 100, 101}, {100, 101, 200} and {101, 200, 300}
Method 1(Brute Force)
- Approach: The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from an array. The innermost loop checks for the triangle property which specifies the sum of any two sides must be greater than the value of the third side).
- Algorithm:
- Run three nested loops each loop starting from the index of the previous loop to end of array i.e run first loop from 0 to n, loop j from i to n and k from j to n.
- Check if array[i] + array[j] > array[k], array[i] + array[k] > array[j], array[k] + array[j] > array[i], i.e. sum of two sides is greater than the third
- if all three conditions match, increase the count.
- Print the count
- Implementation:
C++
// C++ code to count the number of // possible triangles using brute // force approach #include <bits/stdc++.h> using namespace std; // Function to count all possible // triangles with arr[] elements int findNumberOfTriangles( int arr[], int n) { // Count of triangles int count = 0; // The three loops select three // different values from array for ( int i = 0; i < n; i++) { for ( int j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for ( int k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof (arr) / sizeof (arr[0]); cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0; } |
Java
// Java code to count the number of // possible triangles using brute // force approach import java.io.*; import java.util.*; class GFG { // Function to count all possible // triangles with arr[] elements static int findNumberOfTriangles( int arr[], int n) { // Count of triangles int count = 0 ; // The three loops select three // different values from array for ( int i = 0 ; i < n; i++) { for ( int j = i + 1 ; j < n; j++) { // The innermost loop checks for // the triangle property for ( int k = j + 1 ; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code public static void main(String[] args) { int arr[] = { 10 , 21 , 22 , 100 , 101 , 200 , 300 }; int size = arr.length; System.out.println( "Total number of triangles possible is " + findNumberOfTriangles(arr, size)); } } // This code is contributed by shubhamsingh10 |
Python3
# Python3 code to count the number of # possible triangles using brute # force approach # Function to count all possible # triangles with arr[] elements def findNumberOfTriangles(arr, n): # Count of triangles count = 0 # The three loops select three # different values from array for i in range (n): for j in range (i + 1 , n): # The innermost loop checks for # the triangle property for k in range (j + 1 , n): # Sum of two sides is greater # than the third if (arr[i] + arr[j] > arr[k] and arr[i] + arr[k] > arr[j] and arr[k] + arr[j] > arr[i]): count + = 1 return count # Driver code arr = [ 10 , 21 , 22 , 100 , 101 , 200 , 300 ] size = len (arr) print ( "Total number of triangles possible is" , findNumberOfTriangles(arr, size)) # This code is contributed by shubhamsingh10 |
C#
// C# code to count the number of // possible triangles using brute // force approach using System; class GFG{ // Function to count all possible // triangles with arr[] elements static int findNumberOfTriangles( int [] arr, int n) { // Count of triangles int count = 0; // The three loops select three // different values from array for ( int i = 0; i < n; i++) { for ( int j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for ( int k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver code static public void Main () { int [] arr = { 10, 21, 22, 100, 101, 200, 300 }; int size = arr.Length; Console.WriteLine( "Total number of triangles possible is " +findNumberOfTriangles(arr, size)); } } // This code is contributed by shubhamsingh10 |
Javascript
<script> // Javascript program for the above approach // Function to count all possible // triangles with arr[] elements function findNumberOfTriangles(arr, n) { // Count of triangles let count = 0; // The three loops select three // different values from array for (let i = 0; i < n; i++) { for (let j = i + 1; j < n; j++) { // The innermost loop checks for // the triangle property for (let k = j + 1; k < n; k++) // Sum of two sides is greater // than the third if ( arr[i] + arr[j] > arr[k] && arr[i] + arr[k] > arr[j] && arr[k] + arr[j] > arr[i]) count++; } } return count; } // Driver Code let arr = [ 10, 21, 22, 100, 101, 200, 300 ]; let size = arr.length; document.write( "Total number of triangles possible is " + findNumberOfTriangles(arr, size)); // This code is contributed by souravghosh0416. </script> |
Total number of triangles possible is 6
- Complexity Analysis:
- Time Complexity: O(N^3) where N is the size of input array.
- Space Complexity: O(1)
Method 2: This is a tricky and efficient approach to reduce the time complexity from O(n^3) to O(n^2)where two sides of the triangles are fixed and the count can be found using those two sides.
- Approach: First sort the array in ascending order. Then use two loops. The outer loop to fix the first side and inner loop to fix the second side and then find the farthest index of the third side (greater than indices of both sides) whose length is less than some of the other two sides. So a range of values third sides can be found, where it is guaranteed that its length if greater than the other individual sides but less than the sum of both sides.
- Algorithm: Let a, b and c be three sides. The below condition must hold for a triangle (sum of two sides is greater than the third side)
i) a + b > c
ii) b + c > a
iii) a + c > b
Following are steps to count triangle.- Sort the array in ascending order.
- Now run a nested loop. The outer loop runs from start to end and the innner loop runs from index + 1 of the first loop to the end. Take the loop counter of first loop as i and second loop as j. Take another variable k = i + 2
- Now there is two pointers i and j, where array[i] and array[j] represents two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]
- So when we get the largest value, then the count of third side is k – j, add it to the total count.
- Now sum up for all valid pairs of i and j where i < j
- Implementation:
C++
// C++ program to count number of triangles that can be // formed from given array #include <bits/stdc++.h> using namespace std; /* Following function is needed for library function qsort(). Refer http:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ int comp( const void * a, const void * b) { return *( int *)a > *( int *)b; } // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles( int arr[], int n) { // Sort the array elements in non-decreasing order qsort (arr, n, sizeof (arr[0]), comp); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for ( int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for ( int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count; } // Driver code int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof (arr) / sizeof (arr[0]); cout << "Total number of triangles possible is " << findNumberOfTriangles(arr, size); return 0; } // This code is contributed by rathbhupendra |
C
// C program to count number of triangles that can be // formed from given array #include <stdio.h> #include <stdlib.h> /* Following function is needed for library function qsort(). Refer http:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */ int comp( const void * a, const void * b) { return *( int *)a > *( int *)b; } // Function to count all possible triangles with arr[] // elements int findNumberOfTriangles( int arr[], int n) { // Sort the array elements in non-decreasing order qsort (arr, n, sizeof (arr[0]), comp); // Initialize count of triangles int count = 0; // Fix the first element. We need to run till n-3 // as the other two elements are selected from // arr[i+1...n-1] for ( int i = 0; i < n - 2; ++i) { // Initialize index of the rightmost third // element int k = i + 2; // Fix the second element for ( int j = i + 1; j < n; ++j) { // Find the rightmost element which is // smaller than the sum of two fixed elements // The important thing to note here is, we // use the previous value of k. If value of // arr[i] + arr[j-1] was greater than arr[k], // then arr[i] + arr[j] must be greater than k, // because the array is sorted. while (k < n && arr[i] + arr[j] > arr[k]) ++k; // Total number of possible triangles that can // be formed with the two fixed elements is // k - j - 1. The two fixed elements are arr[i] // and arr[j]. All elements between arr[j+1]/ to // arr[k-1] can form a triangle with arr[i] and arr[j]. // One is subtracted from k because k is incremented // one extra in above while loop. // k will always be greater than j. If j becomes equal // to k, then above loop will increment k, because arr[k] // + arr[i] is always greater than arr[k] if (k > j) count += k - j - 1; } } return count; } // Driver program to test above functionarr[j+1] int main() { int arr[] = { 10, 21, 22, 100, 101, 200, 300 }; int size = sizeof (arr) / sizeof (arr[0]); printf ( "Total number of triangles possible is %d " , findNumberOfTriangles(arr, size)); return 0; } |
Java
// Java program to count number of triangles that can be // formed from given array import java.io.*; import java.util.*; class CountTriangles { // Function to count all possible triangles with arr[] // elements static int findNumberOfTriangles( int arr[]) { int n = arr.length; // Sort the array elements in non-decreasing order Arrays.sort(arr); // Initialize count of triangles int count = 0 ; // Fix the first element. We need to run till n-3 as // the other two elements are selected from arr[i+1...n-1] for ( int i = 0 ; i < n - 2 ; ++i) { // Initialize index of the rightmost third element int k = i + 2 ; // Fix the second element for ( int j = i + 1 ; j < n; ++j) { /* Find the rightmost element which is smaller than the sum of two fixed elements The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while (k < n && arr[i] + arr[j] > arr[k]) ++k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if (k > j) count += k - j - 1 ; } } return count; } public static void main(String[] args) { int arr[] = { 10 , 21 , 22 , 100 , 101 , 200 , 300 }; System.out.println( "Total number of triangles is " + findNumberOfTriangles(arr)); } } /*This code is contributed by Devesh Agrawal*/ |
Python
# Python function to count all possible triangles with arr[] # elements def findnumberofTriangles(arr): # Sort array and initialize count as 0 n = len (arr) arr.sort() count = 0 # Fix the first element. We need to run till n-3 as # the other two elements are selected from arr[i + 1...n-1] for i in range ( 0 , n - 2 ): # Initialize index of the rightmost third element k = i + 2 # Fix the second element for j in range (i + 1 , n): # Find the rightmost element which is smaller # than the sum of two fixed elements # The important thing to note here is, we use # the previous value of k. If value of arr[i] + # arr[j-1] was greater than arr[k], then arr[i] + # arr[j] must be greater than k, because the array # is sorted. while (k < n and arr[i] + arr[j] > arr[k]): k + = 1 # Total number of possible triangles that can be # formed with the two fixed elements is k - j - 1. # The two fixed elements are arr[i] and arr[j]. All # elements between arr[j + 1] to arr[k-1] can form a # triangle with arr[i] and arr[j]. One is subtracted # from k because k is incremented one extra in above # while loop. k will always be greater than j. If j # becomes equal to k, then above loop will increment k, # because arr[k] + arr[i] is always greater than arr[k] if (k>j): count + = k - j - 1 return count # Driver function to test above function arr = [ 10 , 21 , 22 , 100 , 101 , 200 , 300 ] print "Number of Triangles:" , findnumberofTriangles(arr) # This code is contributed by Devesh Agrawal |
C#
// C# program to count number // of triangles that can be // formed from given array using System; class GFG { // Function to count all // possible triangles // with arr[] elements static int findNumberOfTriangles( int [] arr) { int n = arr.Length; // Sort the array elements // in non-decreasing order Array.Sort(arr); // Initialize count // of triangles int count = 0; // Fix the first element. We // need to run till n-3 as // the other two elements are // selected from arr[i+1...n-1] for ( int i = 0; i < n - 2; ++i) { // Initialize index of the // rightmost third element int k = i + 2; // Fix the second element for ( int j = i + 1; j < n; ++j) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while (k < n && arr[i] + arr[j] > arr[k]) ++k; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if (k > j) count += k - j - 1; } } return count; } // Driver Code public static void Main() { int [] arr = { 10, 21, 22, 100, 101, 200, 300 }; Console.WriteLine( "Total number of triangles is " + findNumberOfTriangles(arr)); } } // This code is contributed by anuj_67. |
PHP
<?php // PHP program to count number // of triangles that can be // formed from given array // Function to count all // possible triangles with // arr[] element function findNumberOfTriangles( $arr ) { $n = count ( $arr ); // Sort the array elements // in non-decreasing order sort( $arr ); // Initialize count // of triangles $count = 0; // Fix the first element. // We need to run till n-3 // as the other two elements // are selected from // arr[i+1...n-1] for ( $i = 0; $i < $n - 2; ++ $i ) { // Initialize index of the // rightmost third element $k = $i + 2; // Fix the second element for ( $j = $i + 1; $j < $n ; ++ $j ) { /* Find the rightmost element which is smaller than the sum of two fixed elements. The important thing to note here is, we use the previous value of k. If value of arr[i] + arr[j-1] was greater than arr[k], then arr[i] + arr[j] must be greater than k, because the array is sorted. */ while ( $k < $n && $arr [ $i ] + $arr [ $j ] > $arr [ $k ]) ++ $k ; /* Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr[i] and arr[j]. All elements between arr[j+1] to arr[k-1] can form a triangle with arr[i] and arr[j]. One is subtracted from k because k is incremented one extra in above while loop. k will always be greater than j. If j becomes equal to k, then above loop will increment k, because arr[k] + arr[i] is always/ greater than arr[k] */ if ( $k > $j ) $count += $k - $j - 1; } } return $count ; } // Driver code $arr = array (10, 21, 22, 100, 101, 200, 300); echo "Total number of triangles is " , findNumberOfTriangles( $arr ); // This code is contributed by anuj_67. ?> |
Total number of triangles possible is 6
- Complexity Analysis:
- Time Complexity: O(n^2).
The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2). - Space Complexity: O(1).
No extra space is required. So space complexity is constant
- Time Complexity: O(n^2).
Method 3: The time complexity can be greatly reduced using Two Pointer methods in just two nested loops.
- Approach: First sort the array, and run a nested loop, fix an index and then try to fix an upper and lower index within which we can use all the lengths to form a triangle with that fixed index.
- Algorithm:
- Sort the array and then take three variables l, r and i, pointing to start, end-1 and array element starting from end of the array.
- Traverse the array from end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1
- Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously formed
from a[l+1], a[l+2]…..a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than r - If triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r
- So the overall complexity of iterating
through all array elements reduces.
- Implementation:
C++
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; void CountTriangles(vector< int > A) { int n = A.size(); sort(A.begin(), A.end()); int count = 0; for ( int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] l++; } } cout << "No of possible solutions: " << count; } int main() { vector< int > A = { 4, 3, 5, 7, 6 }; CountTriangles(A); } |
Java
// Java implementation of the above approach import java.util.*; class GFG { static void CountTriangles( int [] A) { int n = A.length; Arrays.sort(A); int count = 0 ; for ( int i = n - 1 ; i >= 1 ; i--) { int l = 0 , r = i - 1 ; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } System.out.print( "No of possible solutions: " + count); } // Driver Code public static void main(String[] args) { int [] A = { 4 , 3 , 5 , 7 , 6 }; CountTriangles(A); } } // This code is contributed by PrinciRaj1992 |
Python3
# Python implementation of the above approach def CountTriangles( A): n = len (A); A.sort(); count = 0 ; for i in range (n - 1 , 0 , - 1 ): l = 0 ; r = i - 1 ; while (l < r): if (A[l] + A[r] > A[i]): # If it is possible with a[l], a[r] # and a[i] then it is also possible # with a[l + 1]..a[r-1], a[r] and a[i] count + = r - l; # checking for more possible solutions r - = 1 ; else : # if not possible check for # higher values of arr[l] l + = 1 ; print ( "No of possible solutions: " , count); # Driver Code if __name__ = = '__main__' : A = [ 4 , 3 , 5 , 7 , 6 ]; CountTriangles(A); # This code is contributed by PrinciRaj1992 |
C#
// C# implementation of the above approach using System; class GFG { static void CountTriangles( int [] A) { int n = A.Length; Array.Sort(A); int count = 0; for ( int i = n - 1; i >= 1; i--) { int l = 0, r = i - 1; while (l < r) { if (A[l] + A[r] > A[i]) { // If it is possible with a[l], a[r] // and a[i] then it is also possible // with a[l+1]..a[r-1], a[r] and a[i] count += r - l; // checking for more possible solutions r--; } else // if not possible check for // higher values of arr[l] { l++; } } } Console.Write( "No of possible solutions: " + count); } // Driver Code public static void Main(String[] args) { int [] A = { 4, 3, 5, 7, 6 }; CountTriangles(A); } } // This code is contributed by Rajput-Ji |
No of possible solutions: 9
- Complexity Analysis:
- Time complexity: O(n^2).
As two nested loops are used, but overall iterations in comparison to above method reduces greatly. - Space Complexity: O(1).
As no extra space is required, so space complexity is constant
- Time complexity: O(n^2).
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.