Prepin
Log in

Given an array of integers, identify a triplet of integers that can create a triangle.

Approach / Explanation

This question requires you to develop an algorithm that can find any potential triplet of integers from an array that can serve as the sides of a triangle. The criterion for three sides to constitute a triangle is that the sum of any two sides must exceed the length of the third side. To tackle this question, keep the following points in mind: You should familiarize yourself with the triangle inequality theorem, which, in this context, asserts that for three numbers to represent the sides of a triangle, the sum of any two numbers must be greater than the third number. You should be capable of iterating through the array in a nested fashion to explore all possible combinations of three integers. Sorting the array may simplify your task since, if a, b, and c are sorted (with a ≤ b ≤ c), they can only form a triangle if a + b > c. This can transform the problem from requiring a three-layer loop to just a two-layer loop.

Suggested Answer

To begin with, sort the provided array, ensuring that its length is at least 3. Iterate through the sorted array, checking each set of three consecutive numbers. If any set fulfills the conditions of the triangle inequality theorem, return those numbers; if none do, return an empty array or "None." Below is an example of Python code: def find_triangle ( arr ) : if len ( arr ) < 3 : return [ ] arr . sort ( ) for i in range ( len ( arr ) - 2 ) : if arr [ i ] + arr [ i + 1 ] > arr [ i + 2 ] : return [ arr [ i ] , arr [ i + 1 ] , arr [ i + 2 ] ] return [ ]

Alternative Answer

As an alternative, you can iterate through the array using three nested loops to generate all possible triplets and verify whether each triplet meets the triangle property. If a valid triplet is found that can form a triangle, return that triplet. This method does not require sorting but has a greater time complexity. Here is an example of Python code: def find_triangle ( arr ) : n = len ( arr ) if n < 3 : return [ ] for i in range ( n - 2 ) : for j in range ( i + 1 , n - 1 ) : for k in range ( j + 1 , n ) : if ( arr [ i ] + arr [ j ] > arr [ k ] ) and ( arr [ i ] + arr [ k ] > arr [ j ] ) and ( arr [ j ] + arr [ k ] > arr [ i ] ) : return [ arr [ i ] , arr [ j ] , arr [ k ] ] return [ ] Both implementations return the first trio of integers from the array that can serve as the sides of a triangle, or an empty array if no such triplet exists. The second method might examine more triplets, especially if a valid triplet is located toward the end of the sorted array.

Question Details

Difficulty & Category

Medium
algorithms

Companies

LinkedIn

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.