πDay 5. Count the number of possible triangles π§
The problem can be found at the following link: Question Link
Please don't block our ads :( οΌ Ad sponsors allow us to make Codeshare free. Hide Ads )
π‘ 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 Walkthrough:
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:
Output:
Explanation: No triangles are possible.
Constraints:
$
3 <= arr.size() <= 10^3$$
1 <= arr[i] <= 10^5$
π― 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.
π Solution Code
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