08. Count the number of possible triangles
The problem can be found at the following link: Question Link
Problem Description
Given an integer array arr[], find the number of triangles that can be formed with three different array elements as the lengths of three sides of the triangle.
A triangle with three given sides is only possible if the sum of any two sides is always greater than the third side.
Example:
Input:
arr[] = [4, 6, 3, 7]Output:
3Explanation: 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:
6Explanation: 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:
Explanation: No triangles are possible.
My Approach
Sorting the Array:
Sort the array to make it easier to check if any three sides can form a valid triangle. Sorting ensures that we can always check for a valid triangle using the largest side as the third side.
Iterating through the Array:
After sorting the array, iterate over it in reverse order to check each possible triplet
(arr[i], arr[l], arr[r])(withlandrstarting from 0 andi-1, respectively).
Checking Triangle Validity:
For each triplet, if
arr[l] + arr[r] > arr[i], then the triplet can form a valid triangle. If this condition holds, increment the count of possible triangles.
Returning the Result:
The result is the final count of all valid triplets that form a triangle.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n^2), where
nis the length of the array, as we iterate over the array and check pairs of elements for each element.Expected Auxiliary Space Complexity: O(1), since we only use a constant amount of additional space for counters and temporary variables.
Code (C)
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated