Counting number of triangle sides in an array in JavaScript

Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first and the only argument.

The task of our function is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.

For example, if the input to the function is ?

const arr = [2, 2, 3, 4];

Then the output should be ?

const output = 3;

Triangle Validity Rule

For three sides to form a valid triangle, they must satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side. For sides a, b, and c (where a ? b ? c), we only need to check if a + b > c.

Output Explanation

Valid combinations are:

2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3

Approach

The algorithm sorts the array first, then uses three nested loops to find valid triangles. For each pair of sides (i, j), it counts how many third sides can form valid triangles using the triangle inequality rule.

Example

Following is the code ?

const arr = [2, 2, 3, 4];

const countTriangle = (arr = []) => {
    arr.sort((a, b) => a - b);
    let k = 2;
    let count = 0;
    
    for (let i = 0; i 

Output

Following is the console output ?

3

How It Works

The algorithm works by:

  • Sorting the array to ensure a ? b ? c for any triplet
  • For each pair (i, j), finding all valid third elements k where arr[i] + arr[j] > arr[k]
  • Using the sorted property to efficiently count valid triangles without checking all combinations

Alternative Brute Force Approach

Here's a simpler but less efficient approach that checks all combinations:

const arr2 = [2, 2, 3, 4];

const countTriangleBruteForce = (arr = []) => {
    let count = 0;
    
    for (let i = 0; i  c && a + c > b && b + c > a) {
                    count++;
                }
            }
        }
    }
    return count;
};

console.log(countTriangleBruteForce(arr2));
3

Comparison

Method Time Complexity Space Complexity
Optimized (sorted) O(n²) O(1)
Brute Force O(n³) O(1)

Conclusion

The optimized approach using sorting and two pointers efficiently counts valid triangles in O(n²) time. For large arrays, this is significantly faster than the O(n³) brute force method.

Updated on: 2026-03-15T23:19:00+05:30

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements