![]() |
VOOZH | about |
Given an array of positive integers arr[], count the number of triangles that can be formed with three different array elements as three sides of triangles.
Note: The sum of any two sides of a triangle must be greater than the 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]Input: arr[] = [1, 2, 3]
Output: 0
Examples: No triangles are possible.
Table of Content
A simple approach is to run three nested loops that select three different values from an array. And in the innermost loop, we checks for the triangle property which specifies the sum of any two sides must be greater than the value of the third side.
3
The idea is to first sort the array in ascending order. Then, use two nested loops where the outer loop fixes the first side and the inner loop fixes the second side. For each such pair, perform a binary search to find the farthest valid index for the third side (with an index greater than the first two) whose value is less than the sum of the first two sides. This gives a valid range of choices for the third side that satisfies the required condition. Finally, add the size of this range to the result.
3
The idea is to sort the array to simplify checking the triangle inequality. Then, for each element (treated as the largest side), use two pointers technique to find count of pairs of smaller sides that can form a triangle with it.
For this, the two pointers are initialized as: one pointer (left) starts at index 0, and the other pointer (right) is positioned just before the current largest side (arr[i]).Now, compare the sum of arr[left] + arr[right] with the current largest side (arr[i]):
If the sum is strictly greater than arr[i], a valid triangle can be formed. Count all valid pairs between left and right, then move the right pointer to the left to explore smaller side values.
If the sum is less than arr[i], increment the left pointer to increase the sum and check larger values.
3