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 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)

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.

Method 3: The time complexity can be greatly reduced using Two Pointer methods in just two nested loops.

Article Tags :