Skip to content
Related Articles

Related Articles

Count the number of possible triangles

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 15 Sep, 2022
Improve Article
Save Article

Given an unsorted array of positive integers, find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values, the sum of any of the two values (or sides) must be greater than the third value (or third side). 

Examples: 

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.  

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}

Naive Approach: To solve the problem follow the below idea: 

The brute force method is to run three loops and keep track of the number of triangles possible so far. The three loops select three different values from an array. The innermost loop checks for the triangle property which specifies the sum of any two sides must be greater than the value of the third side).

Follow the given steps to solve the problem:

  • Run three nested loops each loop starting from the index of the previous loop to the end of the array i.e run first loop from 0 to n, loop j from i to n, and k from j to n
  • Check if array[i] + array[j] > array[k], i.e. sum of two sides is greater than the third
  • Check condition 2 for all combinations of sides by interchanging i, j, k
  • If all three conditions match, then increase the count
  • Print the count

Below is the implementation of the above approach:

C++




// C++ code to count the number of possible triangles using
// brute force approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count all possible triangles with arr[]
// elements
int findNumberOfTriangles(int arr[], int n)
{
    // Count of triangles
    int count = 0;
 
    // The three loops select three different values from
    // array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // The innermost loop checks for the triangle
            // property
            for (int k = j + 1; k < n; k++)
 
                // Sum of two sides is greater than the
                // third
                if (arr[i] + arr[j] > arr[k]
                    && arr[i] + arr[k] > arr[j]
                    && arr[k] + arr[j] > arr[i])
                    count++;
        }
    }
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << "Total number of triangles possible is "
         << findNumberOfTriangles(arr, size);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

C




// C code to count the number of possible triangles using
// brute force approach
#include <stdio.h>
 
// Function to count all possible triangles with arr[]
// elements
int findNumberOfTriangles(int arr[], int n)
{
    // Count of triangles
    int count = 0;
 
    // The three loops select three different values from
    // array
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
 
            // The innermost loop checks for the triangle
            // property
            for (int k = j + 1; k < n; k++)
 
                // Sum of two sides is greater than the
                // third
                if (arr[i] + arr[j] > arr[k]
                    && arr[i] + arr[k] > arr[j]
                    && arr[k] + arr[j] > arr[i])
                    count++;
        }
    }
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("Total number of triangles possible is %d ",
           findNumberOfTriangles(arr, size));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

Java




// Java code to count the number of possible triangles using
// brute force approach
import java.io.*;
import java.util.*;
 
class GFG {
 
    // Function to count all possible triangles with arr[]
    // elements
    static int findNumberOfTriangles(int arr[], int n)
    {
        // Sort the array
        Arrays.sort(arr);
        // Count of triangles
        int count = 0;
        // The three loops select three different values
        // from array
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++)
                for (int k = j + 1; k < n; k++)
                    if (arr[i] + arr[j] > arr[k])
                        count++;
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
        int size = arr.length;
 
        // Function call
        System.out.println(
            "Total number of triangles possible is "
            + findNumberOfTriangles(arr, size));
    }
}
 
// This code is contributed by Sania Kumari Gupta

Python3




# Python3 code to count the number of
# possible triangles using brute
# force approach
 
# Function to count all possible
# triangles with arr[] elements
 
 
def findNumberOfTriangles(arr, n):
 
    # Count of triangles
    count = 0
 
    # The three loops select three
    # different values from array
    for i in range(n):
        for j in range(i + 1, n):
 
            # The innermost loop checks for
            # the triangle property
            for k in range(j + 1, n):
 
                # Sum of two sides is greater
                # than the third
                if (arr[i] + arr[j] > arr[k] and
                    arr[i] + arr[k] > arr[j] and
                        arr[k] + arr[j] > arr[i]):
                    count += 1
    return count
 
 
# Driver code
if __name__ == "__main__":
    arr = [10, 21, 22, 100, 101, 200, 300]
    size = len(arr)
 
    # Function call
    print("Total number of triangles possible is",
          findNumberOfTriangles(arr, size))
 
# This code is contributed by shubhamsingh10

C#




// C# code to count the number of
// possible triangles using brute
// force approach
using System;
 
class GFG {
 
    // Function to count all possible
    // triangles with arr[] elements
    static int findNumberOfTriangles(int[] arr, int n)
    {
        // Count of triangles
        int count = 0;
 
        // The three loops select three
        // different values from array
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
 
                // The innermost loop checks for
                // the triangle property
                for (int k = j + 1; k < n; k++)
 
                    // Sum of two sides is greater
                    // than the third
                    if (arr[i] + arr[j] > arr[k]
                        && arr[i] + arr[k] > arr[j]
                        && arr[k] + arr[j] > arr[i])
                        count++;
            }
        }
        return count;
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 10, 21, 22, 100, 101, 200, 300 };
        int size = arr.Length;
 
        // Function call
        Console.WriteLine(
            "Total number of triangles possible is "
            + findNumberOfTriangles(arr, size));
    }
}
 
// This code is contributed by shubhamsingh10

Javascript




<script>
// Javascript program for the above approach
 
// Function to count all possible
// triangles with arr[] elements
function findNumberOfTriangles(arr, n)
{
 
    // Count of triangles
    let count = 0;
 
    // The three loops select three
    // different values from array
    for (let i = 0; i < n; i++)
    {
        for (let j = i + 1; j < n; j++)
        {
 
            // The innermost loop checks for
            // the triangle property
            for (let k = j + 1; k < n; k++)
 
                // Sum of two sides is greater
                // than the third
                if (
                    arr[i] + arr[j] > arr[k]
                    && arr[i] + arr[k] > arr[j]
                    && arr[k] + arr[j] > arr[i])
                    count++;
        }
    }
    return count;
}
 
// Driver Code
    let arr = [ 10, 21, 22, 100, 101, 200, 300 ];
    let size = arr.length;
     
    document.write( "Total number of triangles possible is "+
      findNumberOfTriangles(arr, size));
 
// This code is contributed by souravghosh0416.
</script>

Output

Total number of triangles possible is 6

Time Complexity: O(N3) where N is the size of the input array
Auxiliary Space: O(1)

Count the number of possible triangles using sorting:

To solve the problem follow the below idea: 

First sort the array in ascending order. Then use two loops. The outer loop to fix the first side and the inner loop to fix the second side and then find the farthest index of the third side (greater than indices of both sides) whose length is less than the sum of the other two sides. So a range of values third side can be found, where it is guaranteed that its length is greater than the other individual sides but less than the sum of both sides.

Let a, b, and c be three sides. The below conditions must hold true for a triangle (the sum of two sides is greater than the third side) 

  1. a + b > c 
  2. b + c > a 
  3. a + c > b

Follow the given steps to solve the problem:

  • Sort the array in ascending order.
  • Now run a nested loop. The outer loop runs from start to end and the inner loop runs from index + 1 of the first loop to the end. Take the loop counter of the first loop as i and the second loop as j. Take another variable k = i + 2
  • Now there are two pointers i and j, where array[i] and array[j] represent two sides of the triangles. For a fixed i and j, find the count of third sides which will satisfy the conditions of a triangle. i.e find the largest value of array[k] such that array[i] + array[j] > array[k]
  • So when we get the largest value, then the count of the third side is k – j, add it to the total count.
  • Now sum up for all valid pairs of i and j where i < j

Below is the implementation of the above approach:

C++




// C++ program to count number of triangles that can be
// formed from given array
#include <bits/stdc++.h>
using namespace std;
 
// Function to count all possible triangles with arr[]
// elements
int findNumberOfTriangles(int arr[], int n)
{
    // Sort the array elements in non-decreasing order
    sort(arr, arr + n);
    // Initialize count of triangles
    int count = 0;
    // Fix the first element. We need to run till n-3
    // as the other two elements are selected from
    // arr[i+1...n-1]
    for (int i = 0; i < n - 2; ++i) {
        // Initialize index of the rightmost third
        // element
        int k = i + 2;
 
        // Fix the second element
        for (int j = i + 1; j < n; ++j) {
            // Find the rightmost element which is smaller
            // than the sum of two fixed elements The
            // important thing to note here is, we use the
            // previous value of k. If value of arr[i] +
            // arr[j-1] was greater than arr[k], then arr[i]
            // + arr[j] must be greater than k, because the
            // array is sorted.
            while (k < n && arr[i] + arr[j] > arr[k])
                ++k;
 
            // Total number of possible triangles that can
            // be formed with the two fixed elements is
            // k - j - 1. The two fixed elements are arr[i]
            // and arr[j]. All elements between arr[j+1]/ to
            // arr[k-1] can form a triangle with arr[i] and
            // arr[j]. One is subtracted from k because k is
            // incremented one extra in above while loop. k
            // will always be greater than j. If j becomes
            // equal to k, then above loop will increment k,
            // because arr[k]
            // + arr[i] is always greater than arr[k]
            if (k > j)
                count += k - j - 1;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << "Total number of triangles possible is "
         << findNumberOfTriangles(arr, size);
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

C




// C program to count number of triangles that can be
// formed from given array
#include <stdio.h>
#include <stdlib.h>
 
/* Following function is needed for library function
qsort(). Refer
http:// www.cplusplus.com/reference/clibrary/cstdlib/qsort/
*/
int comp(const void* a, const void* b)
{
    return *(int*)a > *(int*)b;
}
 
// Function to count all possible triangles with arr[]
// elements
int findNumberOfTriangles(int arr[], int n)
{
    // Sort the array elements in non-decreasing order
    qsort(arr, n, sizeof(arr[0]), comp);
 
    // Initialize count of triangles
    int count = 0;
 
    // Fix the first element. We need to run till n-3
    // as the other two elements are selected from
    // arr[i+1...n-1]
    for (int i = 0; i < n - 2; ++i) {
        // Initialize index of the rightmost third
        // element
        int k = i + 2;
 
        // Fix the second element
        for (int j = i + 1; j < n; ++j) {
            // Find the rightmost element which is
            // smaller than the sum of two fixed elements
            // The important thing to note here is, we
            // use the previous value of k. If value of
            // arr[i] + arr[j-1] was greater than arr[k],
            // then arr[i] + arr[j] must be greater than k,
            // because the array is sorted.
            while (k < n && arr[i] + arr[j] > arr[k])
                ++k;
 
            // Total number of possible triangles that can
            // be formed with the two fixed elements is
            // k - j - 1. The two fixed elements are arr[i]
            // and arr[j]. All elements between arr[j+1]/ to
            // arr[k-1] can form a triangle with arr[i] and
            // arr[j]. One is subtracted from k because k is
            // incremented one extra in above while loop. k
            // will always be greater than j. If j becomes
            // equal to k, then above loop will increment k,
            // because arr[k]
            // + arr[i] is always greater than arr[k]
            if (k > j)
                count += k - j - 1;
        }
    }
 
    return count;
}
 
// Driver code
int main()
{
    int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    printf("Total number of triangles possible is %d ",
           findNumberOfTriangles(arr, size));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta

Java




// Java program to count number of triangles that can be
// formed from given array
import java.io.*;
import java.util.*;
 
class CountTriangles {
    // Function to count all possible triangles with arr[]
    // elements
    static int findNumberOfTriangles(int arr[])
    {
        int n = arr.length;
        // Sort the array elements in non-decreasing order
        Arrays.sort(arr);
 
        // Initialize count of triangles
        int count = 0;
 
        // Fix the first element. We need to run till n-3 as
        // the other two elements are selected from
        // arr[i+1...n-1]
        for (int i = 0; i < n - 2; ++i) {
            // Initialize index of the rightmost third
            // element
            int k = i + 2;
 
            // Fix the second element
            for (int j = i + 1; j < n; ++j) {
                // Find the rightmost element which is
                // smaller than the sum of two fixed
                // elements The important thing to note here
                // is, we use the previous value of k. If
                // value of arr[i] + arr[j-1] was greater
                // than arr[k], then arr[i] + arr[j] must be
                // greater than k, because the array is
                // sorted.
                while (k < n && arr[i] + arr[j] > arr[k])
                    ++k;
 
                // Total number of possible triangles that
                // can be formed with the two fixed elements
                // is k - j - 1. The two fixed elements are
                // arr[i] and arr[j]. All elements between
                // arr[j+1] to arr[k-1] can form a triangle
                // with arr[i] and arr[j]. One is subtracted
                // from k because k is incremented one extra
                // in above while loop. k will always be
                // greater than j. If j becomes equal to k,
                // then above loop will increment k, because
                // arr[k] + arr[i] is always/ greater than
                // arr[k]
                if (k > j)
                    count += k - j - 1;
            }
        }
        return count;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 10, 21, 22, 100, 101, 200, 300 };
 
        // Function call
        System.out.println("Total number of triangles is "
                           + findNumberOfTriangles(arr));
    }
}
 
// This code is contributed by Sania Kumari Gupta

Python3




# Python3 function to count all possible triangles with arr[]
# elements
 
 
def findnumberofTriangles(arr):
 
    # Sort array and initialize count as 0
    n = len(arr)
    arr.sort()
    count = 0
 
    # Fix the first element. We need to run till n-3 as
    # the other two elements are selected from arr[i + 1...n-1]
    for i in range(0, n-2):
 
        # Initialize index of the rightmost third element
        k = i + 2
 
        # Fix the second element
        for j in range(i + 1, n):
 
            # Find the rightmost element which is smaller
            # than the sum of two fixed elements
            # The important thing to note here is, we use
            # the previous value of k. If value of arr[i] +
            # arr[j-1] was greater than arr[k], then arr[i] +
            # arr[j] must be greater than k, because the array
            # is sorted.
            while (k < n and arr[i] + arr[j] > arr[k]):
                k += 1
 
            # Total number of possible triangles that can be
            # formed with the two fixed elements is k - j - 1.
            # The two fixed elements are arr[i] and arr[j]. All
            # elements between arr[j + 1] to arr[k-1] can form a
            # triangle with arr[i] and arr[j]. One is subtracted
            # from k because k is incremented one extra in above
            # while loop. k will always be greater than j. If j
            # becomes equal to k, then above loop will increment k,
            # because arr[k] + arr[i] is always greater than arr[k]
            if(k > j):
                count += k - j - 1
 
    return count
 
 
# Driver code
if __name__ == "__main__":
    arr = [10, 21, 22, 100, 101, 200, 300]
 
    # Function call
    print("Total number of Triangles:", findnumberofTriangles(arr))
 
# This code is contributed by Devesh Agrawal

C#




// C# program to count number
// of triangles that can be
// formed from given array
using System;
 
class GFG {
    // Function to count all
    // possible triangles
    // with arr[] elements
    static int findNumberOfTriangles(int[] arr)
    {
        int n = arr.Length;
 
        // Sort the array elements
        // in non-decreasing order
        Array.Sort(arr);
 
        // Initialize count
        // of triangles
        int count = 0;
 
        // Fix the first element. We
        // need to run till n-3 as
        // the other two elements are
        // selected from arr[i+1...n-1]
        for (int i = 0; i < n - 2; ++i) {
            // Initialize index of the
            // rightmost third element
            int k = i + 2;
 
            // Fix the second element
            for (int j = i + 1; j < n; ++j) {
                /* Find the rightmost element
                which is smaller than the sum
                of two fixed elements. The
                important thing to note here
                is, we use the previous value
                of k. If value of arr[i] +
                arr[j-1] was greater than arr[k],
                then arr[i] + arr[j] must be
                greater than k, because the
                array is sorted. */
                while (k < n && arr[i] + arr[j] > arr[k])
                    ++k;
 
                /* Total number of possible triangles
                that can be formed with the two
                fixed elements is k - j - 1. The
                two fixed elements are arr[i] and
                arr[j]. All elements between arr[j+1]
                to arr[k-1] can form a triangle with
                arr[i] and arr[j]. One is subtracted
                from k because k is incremented one
                extra in above while loop. k will
                always be greater than j. If j becomes
                equal to k, then above loop will
                increment k, because arr[k] + arr[i]
                is always/ greater than arr[k] */
                if (k > j)
                    count += k - j - 1;
            }
        }
        return count;
    }
 
    // Driver Code
    public static void Main()
    {
        int[] arr = { 10, 21, 22, 100, 101, 200, 300 };
 
        // Function call
        Console.WriteLine("Total number of triangles is "
                          + findNumberOfTriangles(arr));
    }
}
 
// This code is contributed by anuj_67.

PHP




<?php
// PHP program to count number
// of triangles that can be
// formed from given array
 
// Function to count all
// possible triangles with
// arr[] element
function findNumberOfTriangles($arr)
{
    $n = count($arr);
     
    // Sort the array elements
    // in non-decreasing order
    sort($arr);
 
    // Initialize count
    // of triangles
    $count = 0;
 
    // Fix the first element.
    // We need to run till n-3
    // as the other two elements
    // are selected from
    // arr[i+1...n-1]
    for ($i = 0; $i < $n - 2; ++$i)
    {
        // Initialize index of the
        // rightmost third element
        $k = $i + 2;
 
        // Fix the second element
        for ($j = $i + 1; $j < $n; ++$j)
        {
            /* Find the rightmost element
            which is smaller than the sum
            of two fixed elements. The
            important thing to note here
            is, we use the previous value
            of k. If value of arr[i] +
            arr[j-1] was greater than
            arr[k], then arr[i] +
            arr[j] must be greater than k,
            because the array is sorted. */
            while ($k < $n && $arr[$i] +
                            $arr[$j] > $arr[$k])
                ++$k;
 
        /* Total number of possible
            triangles that can be
            formed with the two fixed
            elements is k - j - 1.
            The two fixed elements are
            arr[i] and arr[j]. All
            elements between arr[j+1]
            to arr[k-1] can form a
            triangle with arr[i] and
            arr[j]. One is subtracted
            from k because k is incremented
            one extra in above while loop.
            k will always be greater than j.
            If j becomes equal to k, then
            above loop will increment k,
            because arr[k] + arr[i] is
            always/ greater than arr[k] */
            if($k>$j)
            $count += $k - $j - 1;
        }
    }
    return $count;
}
 
// Driver code
$arr = array(10, 21, 22, 100,
            101, 200, 300);
 
// Function call
echo"Total number of triangles is ",
        findNumberOfTriangles($arr);
 
// This code is contributed by anuj_67.
?>

Javascript




<script>
 
// Javascript program to count number of triangles that can be
// formed from given array
 
 
// Function to count all possible triangles with arr[]
// elements
function findNumberOfTriangles(arr)
{
    let n = arr.length;
    // Sort the array elements in non-decreasing order
    arr.sort((a, b) => a-b);
 
    // Initialize count of triangles
    let count = 0;
 
    // Fix the first element. We
        // need to run till n-3 as
        // the other two elements are
        // selected from arr[i+1...n-1]
        for (let i = 0; i < n - 2; ++i) {
            // Initialize index of the
            // rightmost third element
            let k = i + 2;
        // Fix the second element
        for (let j = i + 1; j < n; ++j) {
            // Find the rightmost element which is
            // smaller than the sum of two fixed elements
            // The important thing to note here is, we
            // use the previous value of k. If value of
            // arr[i] + arr[j-1] was greater than arr[k],
            // then arr[i] + arr[j] must be greater than k,
            // because the array is sorted.
            while (k < n && arr[i] + arr[j] > arr[k])
                ++k;
 
            // Total number of possible triangles that can
            // be formed with the two fixed elements is
            // k - j - 1. The two fixed elements are arr[i]
            // and arr[j]. All elements between arr[j+1]/ to
            // arr[k-1] can form a triangle with arr[i] and arr[j].
            // One is subtracted from k because k is incremented
            // one extra in above while loop.
            // k will always be greater than j. If j becomes equal
            // to k, then above loop will increment k, because arr[k]
            // + arr[i] is always greater than arr[k]
            if (k > j)
                count += k - j - 1;
        }
    }
 
    return count;
}
 
// Driver code
 
    let arr = [ 10, 21, 22, 100, 101, 200, 300 ];
    let size = arr.length;
 
    document.write("Total number of triangles possible is " + findNumberOfTriangles(arr, size));
 
// This code is contributed by Manoj
 
</script>

Output

Total number of triangles possible is 6

Time Complexity: O(N2). The time complexity looks more because of 3 nested loops. It can be observed that k is initialized only once in the outermost loop. The innermost loop executes at most O(n) time for every iteration of the outermost loop, because k starts from i+2 and goes up to n for all values of j. Therefore, the time complexity is O(n^2).
Auxiliary Space: O(1), No extra space is required. So space complexity is constant

Count the number of possible triangles using two pointer approach:

To solve the problem follow the below idea: 

First, sort the array, and run a nested loop, fix an index, and then try to fix an upper and lower index within which we can use all the lengths to form a triangle with that fixed index.

Follow the given steps to solve the problem:

  • Sort the array and then take three variables l, r, and i, pointing to start, end-1, and array element starting from the end of the array.
  • Traverse the array from the end (n-1 to 1), and for each iteration keep the value of l = 0 and r = i-1
  • Now if a triangle can be formed using arr[l] and arr[r] then triangles can obviously be formed
    from a[l+1], a[l+2]…..a[r-1], arr[r] and a[i], because the array is sorted , which can be directly calculated using (r-l). and then decrement the value of r and continue the loop till l is less than r
  • If a triangle cannot be formed using arr[l] and arr[r] then increment the value of l and continue the loop till l is less than r 
  • So the overall complexity of iterating 
    through all array elements reduces

Below is the implementation of the above approach:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
void CountTriangles(vector<int> A)
{
 
    int n = A.size();
 
    sort(A.begin(), A.end());
 
    int count = 0;
 
    for (int i = n - 1; i >= 1; i--) {
        int l = 0, r = i - 1;
        while (l < r) {
            if (A[l] + A[r] > A[i]) {
 
                // If it is possible with a[l], a[r]
                // and a[i] then it is also possible
                // with a[l+1]..a[r-1], a[r] and a[i]
                count += r - l;
 
                // checking for more possible solutions
                r--;
            }
            else
 
                // if not possible check for
                // higher values of arr[l]
                l++;
        }
    }
    cout << "No of possible solutions: " << count;
}
 
// Driver code
int main()
{
 
    vector<int> A = { 10, 21, 22, 100, 101, 200, 300 };
 
    // Function call
    CountTriangles(A);
}

Java




// Java implementation of the above approach
import java.util.*;
 
class GFG {
    static void CountTriangles(int[] A)
    {
        int n = A.length;
 
        Arrays.sort(A);
 
        int count = 0;
 
        for (int i = n - 1; i >= 1; i--) {
            int l = 0, r = i - 1;
            while (l < r) {
                if (A[l] + A[r] > A[i]) {
 
                    // If it is possible with a[l], a[r]
                    // and a[i] then it is also possible
                    // with a[l+1]..a[r-1], a[r] and a[i]
                    count += r - l;
 
                    // checking for more possible solutions
                    r--;
                }
                else // if not possible check for
                // higher values of arr[l]
                {
                    l++;
                }
            }
        }
        System.out.print("No of possible solutions: "
                         + count);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] A = { 10, 21, 22, 100, 101, 200, 300 };
 
        // Function call
        CountTriangles(A);
    }
}
 
// This code is contributed by PrinciRaj1992

Python3




# Python implementation of the above approach
def CountTriangles(A):
 
    n = len(A)
 
    A.sort()
 
    count = 0
 
    for i in range(n - 1, 0, -1):
        l = 0
        r = i - 1
        while(l < r):
            if(A[l] + A[r] > A[i]):
 
                # If it is possible with a[l], a[r]
                # and a[i] then it is also possible
                # with a[l + 1]..a[r-1], a[r] and a[i]
                count += r - l
 
                # checking for more possible solutions
                r -= 1
 
            else:
 
                # if not possible check for
                # higher values of arr[l]
                l += 1
    print("No of possible solutions: ", count)
 
 
# Driver Code
if __name__ == '__main__':
 
    A = [10, 21, 22, 100, 101, 200, 300]
 
    # Function call
    CountTriangles(A)
 
# This code is contributed by PrinciRaj1992

C#




// C# implementation of the above approach
using System;
 
class GFG {
    static void CountTriangles(int[] A)
    {
        int n = A.Length;
 
        Array.Sort(A);
 
        int count = 0;
 
        for (int i = n - 1; i >= 1; i--) {
            int l = 0, r = i - 1;
            while (l < r) {
                if (A[l] + A[r] > A[i]) {
 
                    // If it is possible with a[l], a[r]
                    // and a[i] then it is also possible
                    // with a[l+1]..a[r-1], a[r] and a[i]
                    count += r - l;
 
                    // checking for more possible solutions
                    r--;
                }
                else // if not possible check for
                // higher values of arr[l]
                {
                    l++;
                }
            }
        }
        Console.Write("No of possible solutions: " + count);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] A = { 10, 21, 22, 100, 101, 200, 300 };
 
        // Function call
        CountTriangles(A);
    }
}
 
// This code is contributed by Rajput-Ji

Javascript




<script>
// javascript implementation of the above approach
    function CountTriangles(A) {
        var n = A.length;
 
        A.sort();
 
        var count = 0;
 
        for (i = n - 1; i >= 1; i--) {
            var l = 0, r = i - 1;
            while (l < r) {
                if (A[l] + A[r] > A[i]) {
 
                    // If it is possible with a[l], a[r]
                    // and a[i] then it is also possible
                    // with a[l+1]..a[r-1], a[r] and a[i]
                    count += r - l;
 
                    // checking for more possible solutions
                    r--;
                } else // if not possible check for
                // higher values of arr[l]
                {
                    l++;
                }
            }
        }
        document.write("No of possible solutions: " + count);
    }
 
    // Driver Code
        var A = [ 10, 21, 22, 100, 101, 200, 300 ];
        CountTriangles(A);
 
// This code is contributed by aashish1995
</script>

Output

No of possible solutions: 6

Time complexity: O(N2).  As two nested loops are used, overall iterations in comparison to the above method reduces greatly.
Auxiliary Space: O(1).  As no extra space is required, Auxiliary Space is constant


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!