879263. Count the number of possible triangles

Medium

Count the number of possible triangles

Summary

Given an array of integers, count the total number of possible triangles that can be formed using these integers as side lengths. The problem is to find out how many unique triangle combinations are possible from the given set.

Detailed Explanation

The approach for solving this problem is quite straightforward. We need to calculate the number of ways we can arrange three sides in a triangle and multiply it by the total number of possible triangles that can be formed using these integers as side lengths.

Here's how you can do it:

  1. Iterate through the array, considering each triplet (three elements) as potential sides of a triangle.
  2. For each triplet, check if they form a valid triangle (i.e., the sum of two sides is greater than the third side). If not, skip to the next iteration.
  3. If it's a valid triangle, increment a counter for the total number of possible triangles.

Time Complexity: The time complexity is O(n^2) where n is the size of the input array. This is because we are iterating through each element in the array and considering every triplet as potential sides of a triangle.

Space Complexity: The space complexity is O(1), which means that it doesn't depend on the size of the input array. This is because we are only using a constant amount of space to store our counter.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.Arrays;

public class Main {
    public static int countPossibleTriangles(int[] arr) {
        Arrays.sort(arr);
        int count = 0;
        for (int i = 0; i < arr.length - 2; i++) {
            int left = i + 1;
            int right = arr.length - 1;
            while (left < right) {
                if (arr[i] + arr[left] > arr[right]) {
                    count += right - left;
                    left++;
                } else {
                    right--;
                }
            }
        }
        return count;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println(countPossibleTriangles(arr));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.