27. Count the Number of Possible Triangles
β GFG solution to count possible triangles problem: find number of valid triangles using triangle inequality theorem with efficient two-pointer technique. π
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 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 (Triangle Inequality Theorem).
For three sides a, b, and c to form a valid triangle:
a + b > ca + c > bb + c > a
π Examples
Example 1
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 since 3 + 4 = 7, which violates the triangle inequality.Example 2
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].Example 3
Input: arr[] = [1, 2, 3]
Output: 0
Explanation: No triangles are possible since 1 + 2 = 3, which doesn't satisfy the strict inequality.π Constraints
$1 \le \text{arr.size()} \le 10^3$
$0 \le \text{arr}[i] \le 10^5$
β
My Approach
The optimal approach uses Sorting combined with Two Pointers technique to efficiently count valid triangles:
Sorting + Two Pointers (Backward Iteration)
Sort the Array:
Sort the array in ascending order to apply triangle inequality efficiently.
After sorting, for any three elements at indices
i < j < k, we havearr[i] β€ arr[j] β€ arr[k].
Fix the Largest Side:
Iterate from the largest element backwards (index
kfromn-1to2).Fix
arr[k]as the largest side of potential triangles.
Apply Triangle Inequality:
For a sorted array, if
arr[i] + arr[j] > arr[k](wherei < j < k), then all elements betweeniandjwill also satisfy this condition witharr[j].Use two pointers:
i = 0(left) andj = k-1(right).
Count Valid Triangles:
If
arr[i] + arr[j] > arr[k]: All triangles formed by fixingjandk, and choosing any element from indexitoj-1are valid. Add(j - i)to count.If
arr[i] + arr[j] β€ arr[k]: Move left pointer right to increase the sum.
Optimize with Two Pointers:
Move pointers based on triangle inequality validation to avoid redundant checks.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΒ²), where n is the size of the array. The outer loop runs n times, and the inner two-pointer traversal takes O(n) time for each iteration. Sorting takes O(n log n), but the overall complexity is dominated by O(nΒ²).
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables. The sorting is typically done in-place.
π§βπ» Code (C++)
class Solution {
public:
int countTriangles(vector<int>& a) {
sort(a.begin(), a.end());
int c = 0, n = a.size();
for (int k = n - 1; k >= 2; --k) {
int i = 0, j = k - 1;
while (i < j) {
if (a[i] + a[j] > a[k]) {
c += j - i;
--j;
} else ++i;
}
}
return c;
}
};β Code (Java)
class Solution {
public int countTriangles(int[] a) {
Arrays.sort(a);
int c = 0, n = a.length;
for (int k = n - 1; k >= 2; --k) {
int i = 0, j = k - 1;
while (i < j) {
if (a[i] + a[j] > a[k]) {
c += j - i;
--j;
} else ++i;
}
}
return c;
}
}π Code (Python)
class Solution:
def countTriangles(self, a):
a.sort()
c, n = 0, len(a)
for k in range(n - 1, 1, -1):
i, j = 0, k - 1
while i < j:
if a[i] + a[j] > a[k]:
c += j - i
j -= 1
else:
i += 1
return cπ§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated