AlgoMaster Logo

Classify Triangle

Last Updated: June 7, 2026

easy
2 min read

Understanding the Problem

The problem has two layers. First confirm there is a triangle at all. Three lengths that violate the triangle inequality do not form a shape, so they get the label "Invalid" and never reach the classification step.

Once validity is settled, classification depends only on how many sides are equal. All three equal is equilateral, exactly two equal is isosceles, and none equal is scalene. The order of the checks matters: an equilateral triangle also has two equal sides, so test for all-three-equal first, or it gets mislabeled as isosceles.

Key Constraints:

  • Validity comes first → Always run the triangle inequality before classifying. A degenerate set of lengths should return "Invalid" regardless of which sides match.
  • Equilateral is a special case of equal sides → Test all-three-equal before any-two-equal, otherwise an equilateral triangle would be caught by the isosceles branch.
  • Equality is exact here → The inputs are treated as exact values, so direct comparison decides which sides match.

Approach 1: Validate, Then Classify

Intuition

The triangle inequality is the concrete validity test: each pair of sides must sum to strictly more than the third. If any pair fails, return "Invalid" and stop.

For valid lengths, check equalities from most specific to least specific. All three equal is equilateral. Not all three but at least one pair equal is isosceles. No pair equal is scalene. This ordering keeps the equilateral case out of the isosceles branch.

Algorithm

  1. Check the triangle inequality. If any pair of sides does not sum to strictly more than the third, return "Invalid".
  2. If a, b, and c are all equal, return "Equilateral".
  3. Otherwise, if any two of the three sides are equal, return "Isosceles".
  4. Otherwise, return "Scalene".

Example Walkthrough

Input:

5
a
5
b
8
c

The sides are 5, 5, and 8. First check validity: 5 + 5 > 8 gives 10 > 8 which is true, 5 + 8 > 5 is true, and 5 + 8 > 5 is true, so the lengths form a real triangle. Now classify. Are all three equal? No, since 8 differs from 5. Are any two equal? Yes, a and b are both 5. That makes exactly two sides equal, so the triangle is isosceles.

0
I
1
s
2
o
3
s
4
c
5
e
6
l
7
e
8
s
output

Code