Counting Triangle Triplets

Easy
0/40
0 upvote
Asked in company
Standard Chartered

Problem statement

You are given an integer array nums representing possible side lengths. Your task is to count the number of unique triplets (i, j, k) with i < j < k that can be chosen from the array to form the sides of a valid triangle.


A triangle is considered valid if the sum of the lengths of any two sides is strictly greater than the length of the third side.


Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer 'N', the size of the array.

The second line contains 'N' space-separated non-negative integers, representing the elements of the nums array.


Output Format:
Print a single integer representing the total number of valid triangle triplets.


Note:
The condition for three sides a, b, and c to form a triangle is a + b > c, a + c > b, and b + c > a.
Sample Input 1:
4
2 2 3 4


Sample Output 1:
3


Explanation for Sample 1:
First, sort the array: `{2, 2, 3, 4}`. We find triplets `(a, b, c)` where `a + b > c`.
1.  Fix `c = 4` (the last element). We need pairs `(a, b)` from `{2, 2, 3}`.
    - The pairs `{2, 3}` (from index 0 and 2) works since `2+3 > 4`.
    - The pairs `{2, 3}` (from index 1 and 2) works since `2+3 > 4`.
2.  Fix `c = 3` (the element at index 2). We need pairs `(a, b)` from `{2, 2}`.
    - The pair `{2, 2}` works since `2+2 > 3`.
The total count of valid combinations is 3.


Sample Input 2:
3
1 2 10


Sample Output 2:
0


Explanation for Sample 2:
The only triplet is `{1, 2, 10}`. Since `1 + 2` is not greater than `10`, no valid triangle can be formed.


Expected Time Complexity:
The expected time complexity is O(N^2).


Constraints:
1 <= N <= 1000
0 <= nums[i] <= 1000

Time limit: 1 sec
Approaches (1)
Counting Triangle Triplets
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Counting Triangle Triplets
Full screen
Console