Possible to form a triangle from array values
Last Updated :
19 Sep, 2023
Given an array of integers, we need to find out whether it is possible to construct at least one non-degenerate triangle using array values as its sides. In other words, we need to find out 3 such array indices which can become sides of a non-degenerate triangle.
Examples :
Input : [4, 1, 2]
Output : No
No triangle is possible from given
array values
Input : [5, 4, 3, 1, 2]
Output : Yes
Sides of possible triangle are 2 3 4
For a non-degenerate triangle, its sides should follow these constraints,
A + B > C and
B + C > A and
C + A > B
where A, B and C are length of sides of the triangle.
The task is to find any triplet from array that satisfies above condition.
A Simple Solution is to generate all triplets and for every triplet check if it forms a triangle or not by checking above three conditions.
An Efficient Solution is use sorting. First, we sort the array then we loop once and we will check three consecutive elements of this array if any triplet satisfies arr[i] + arr[i+1] > arr[i+2], then we will output that triplet as our final result.
Why checking only 3 consecutive elements will work instead of trying all possible triplets of sorted array?
Let we are at index i and 3 line segments are arr[i], arr[i + 1] and arr[i + 2] with relation arr[i] < arr[i+1] < arr[i+2], If they can’t form a non-degenerate triangle, Line segments of lengths arr[i-1], arr[i+1] and arr[i+2] or arr[i], arr[i+1] and arr[i+3] can’t form a non-degenerate triangle also because sum of arr[i-1] and arr[i+1] will be even less than sum of arr[i] and arr[i+1] in first case and sum of arr[i] and arr[i+1] must be less than arr[i+3] in second case, So we don’t need to try all the combinations, we will try just 3 consecutive indices of array in sorted form.
The total complexity of below solution is O(n log n). And auxiliary space is O(1).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool isPossibleTriangle( int arr[], int N)
{
if (N < 3)
return false ;
sort(arr, arr + N);
for ( int i = 0; i < N - 2; i++)
if (arr[i] + arr[i + 1] > arr[i + 2])
return true ;
return false ;
}
int main()
{
int arr[] = { 5, 4, 3, 1, 2 };
int N = sizeof (arr) / sizeof ( int );
isPossibleTriangle(arr, N) ? cout << "Yes" : cout << "No" ;
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int cmpfunc( const void * a, const void * b)
{
return (*( int *)a - *( int *)b);
}
bool isPossibleTriangle( int arr[], int N)
{
if (N < 3)
return false ;
qsort (arr, N, sizeof ( int ), cmpfunc);
for ( int i = 0; i < N - 2; i++)
if (arr[i] + arr[i + 1] > arr[i + 2])
return true ;
return false ;
}
int main()
{
int arr[] = { 5, 4, 3, 1, 2 };
int N = sizeof (arr) / sizeof ( int );
isPossibleTriangle(arr, N) ? printf ( "Yes" ) : printf ( "No" );
return 0;
}
|
JAVA
import java.io.*;
import java.util.Arrays;
class GFG {
static boolean isPossibleTriangle( int [] arr, int N)
{
if (N < 3 )
return false ;
Arrays.sort(arr);
for ( int i = 0 ; i < N - 2 ; i++)
if (arr[i] + arr[i + 1 ] > arr[i + 2 ])
return true ;
return false ;
}
static public void main(String[] args)
{
int [] arr = { 5 , 4 , 3 , 1 , 2 };
int N = arr.length;
if (isPossibleTriangle(arr, N))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python
def isPossibleTriangle (arr , N):
if N < 3 :
return False
arr.sort()
for i in range (N - 2 ):
if arr[i] + arr[i + 1 ] > arr[i + 2 ]:
return True
arr = [ 5 , 4 , 3 , 1 , 2 ]
N = len (arr)
print ( "Yes" if isPossibleTriangle(arr, N) else "No" )
|
C#
using System;
class GFG
{
static bool isPossibleTriangle( int []arr,
int N)
{
if (N < 3)
return false ;
Array.Sort(arr);
for ( int i = 0; i < N - 2; i++)
if (arr[i] + arr[i + 1] > arr[i + 2])
return true ;
return false ;
}
static public void Main ()
{
int []arr = {5, 4, 3, 1, 2};
int N = arr.Length;
if (isPossibleTriangle(arr, N))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function isPossibleTriangle( $arr , $N )
{
if ( $N < 3)
return false;
sort( $arr );
for ( $i = 0; $i < $N - 2; $i ++)
if ( $arr [ $i ] + $arr [ $i + 1] > $arr [ $i + 2])
return true;
}
$arr = array (5, 4, 3, 1, 2);
$N = count ( $arr );
if (isPossibleTriangle( $arr , $N ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function isPossibleTriangle(arr, N)
{
if (N < 3)
return false ;
arr.sort();
for (let i = 0; i < N - 2; i++)
if (arr[i] + arr[i + 1] > arr[i + 2])
return true ;
return false ;
}
let arr = [5, 4, 3, 1, 2];
let N = arr.length;
if (isPossibleTriangle(arr, N))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity : O(NlogN), here N is size of array.
Auxiliary Space : O(1),since no extra space is used.
Similar Reads
Program to print Sum Triangle for a given array
Given a array, write a program to construct a triangle where last row contains elements of given array, every element of second last row contains sum of below two elements and so on. Example: Input: arr[] = {4, 7, 3, 6, 7};Output:8140 4121 19 2211 10 9 134 7 3 6 7 Input: {10, 40, 50}Output:14050 901
9 min read
Sum triangle from array
Given an array of integers, print a sum triangle from it such that the first level has all array elements. From then, at each level number of elements is one less than the previous level and elements at the level is be the Sum of consecutive two elements in the previous level. Example : Input : A =
11 min read
Largest lexicographic triplet from a given Array that forms a triangle
Given an array arr[], the task is to find the lexicographically largest triplet in that array that can form a triangle. If no such triplet exists, print -1.Example: Input: arr[] = { 4, 2, 10, 3, 5 } Output: 3 4 5 Explanation: The lexicographically largest triplet is (4, 5, 10). But it does not form
5 min read
Maximum Perimeter Triangle from array
Given an array arr[] of positive integers. Find out the maximum perimeter of the triangle from the array. Note: Return -1, if it is not possible to construct a triangle. Examples: Input: arr[] = [6, 1, 6, 5, 8, 4]Output: 20Explanation: Triangle formed by 8,6 & 6 has perimeter 20, which is the ma
8 min read
Program to find area of a triangle
Given the sides of a triangle, the task is to find the area of this triangle. Examples : Input : a = 5, b = 7, c = 8 Output : Area of a triangle is 17.320508 Input : a = 3, b = 4, c = 5 Output : Area of a triangle is 6.000000Recommended PracticeArea of a triangleTry It! Approach: The area of a trian
10 min read
Number of possible Triangles in a Cartesian coordinate system
Given n points in a Cartesian coordinate system. Count the number of triangles formed. Examples: Input : point[] = {(0, 0), (1, 1), (2, 0), (2, 2) Output : 3 Three triangles can be formed from above points. A simple solution is to check if the determinant of the three points selected is non-zero or
7 min read
Forming triangles using points on a square
Given a square with N points on each side of the square and none of these points co-incide with the corners of the square. The task is to calculate the total number of triangles that can be formed using these 4 * N points (N points on each side of the square) as vertices of the triangle.Examples: In
3 min read
Program to find the Volume of a Triangular Prism
Given the length, width, and height of a triangular prism, the task is to find the volume of the triangular prism. Examples: Input: l = 18, b = 12, h = 9 Output: Volume of triangular prism: 972 Input: l = 10, b = 8, h = 6 Output: Volume of triangular prism: 240 In mathematics, a triangular prism is
3 min read
JavaScript Program to Count the Number of Possible Triangles in Array
Triangles are basic geometric figures with three sides and three angles. Finding the number of triangles that can be created from a given set of side lengths is a frequent challenge in computational programming. In this article, we'll see how to use a JavaScript array to calculate the total number o
4 min read
Count Possible Triangles
Given an unsorted array of positive integers, the task is to 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 as sides, the sum of the two values (or sides) must always be greater than the thi
15+ min read