Count the number of possible triangles
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 two values (or sides) must be greater than the third value (or third side).
For example, if the input array is {4, 6, 3, 7}, the output should be 3. 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.
As another example, consider the array {10, 21, 22, 100, 101, 200, 300}. 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)
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 array, the innermost loop checks for the triangle property ( the sum of any two sides must be greater than the value of third side).
Time Complexity: O(N^3) where N is the size of input array.
Method 2 (Tricky and Efficient)
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.
1. Sort the array in non-decreasing order.
2. Initialize two pointers ‘i’ and ‘j’ to first and second elements respectively, and initialize count of triangles as 0.
3. Fix ‘i’ and ‘j’ and find the rightmost index ‘k’ (or largest ‘arr[k]’) such that ‘arr[i] + arr[j] > arr[k]’. The number of triangles that can be formed with ‘arr[i]’ and ‘arr[j]’ as two sides is ‘k – j’. Add ‘k – j’ to count of triangles.
Let us consider ‘arr[i]’ as ‘a’, ‘arr[j]’ as b and all elements between ‘arr[j+1]’ and ‘arr[k]’ as ‘c’. The above mentioned conditions (ii) and (iii) are satisfied because ‘arr[i] < arr[j] < arr[k]'. And we check for condition (i) when we pick 'k'
4. Increment ‘j’ to fix the second element again.
Note that in step 3, we can use the previous value of ‘k’. The reason is simple, if we know that the value of ‘arr[i] + arr[j-1]’ is greater than ‘arr[k]’, then we can say ‘arr[i] + arr[j]’ will also be greater than ‘arr[k]’, because the array is sorted in increasing order.
5. If ‘j’ has reached end, then increment ‘i’. Initialize ‘j’ as ‘i + 1’, ‘k’ as ‘i+2’ and repeat the steps 3 and 4.
Following is implementation of the above approach.
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 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 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. ?> |
Output:
Total number of triangles possible is 6
Time Complexity: O(n^2). The time complexity looks more because of 3 nested loops. If we take a closer look at the algorithm, we observe that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of outer most loop, because k starts from i+2 and goes upto n for all values of j. Therefore, the time complexity is O(n^2).
Two Pointer Technique:
The time complexity can be greatly reduced using Two pointer method in just two nested loops.
Lets suppose the array given is {4,3,5,7,6}. On sorting the array becomes {3,4,5,6,7}.
We take three variables l ,r and i, pointing to start , end-1 and array element starting
from end of the array.
Now if we can form triange using arr[l] and arr[r] then we can obviously form triangles
from a[l+1],a[l+2]…..a[r-1], arr[r] and a[i], because the array is sorted
which we can directly calculate using (r-l). So the overall complexity of iterating
through all array elements reduces.
Below is the implementation of the above approach:
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 |
Output:
No of possible solutions: 9
Time complexity: O(n^2), because we use two nested loops , but overall iterations in comparison to
above method reduces greatly.
Source: http://stackoverflow.com/questions/8110538/total-number-of-possible-triangles-from-n-numbers
https://www.geeksforgeeks.org/two-pointers-technique/
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Recommended Posts:
- Count number of right triangles possible with a given perimeter
- Count number of unique Triangles using STL | Set 1 (Using set)
- Find number of unique triangles among given N triangles
- Count of triangles with total n points with m collinear
- Number of triangles after N moves
- Number of triangles that can be formed with given N points
- Number of Triangles in an Undirected Graph
- Number of triangles formed from a set of points on three lines
- Number of possible Triangles in a Cartesian coordinate system
- Number of Isosceles triangles in a binary tree
- Number of triangles in a plane if no more than two points are collinear
- Number of Triangles in Directed and Undirected Graphs
- Number of triangles possible with given lengths of sticks which are powers of 2
- Number of Triangles that can be formed given a set of lines in Euclidean Plane
- Total number of triangles formed when there are H horizontal and V vertical lines



