Classifying Triangles by Lengths
EasyUpdated: Jul 7, 2025
Practice on:
Problem
Table: Triangles
+-------------+------+
| Column Name | Type |
+-------------+------+
| A | int |
| B | int |
| C | int |
+-------------+------+
(A, B, C) is the primary key for this table.
Each row include the lengths of each of a triangle's three sides.
Write a query to find the type of triangle. Output one of the following for each row:
- Equilateral : It's a triangle with
3sides of equal length. - Isosceles : It's a triangle with
2sides of equal length. - Scalene : It's a triangle with
3sides of differing lengths. - Not A Triangle: The given values of
A,B, andCdon't form a triangle.
Return the result table inany order.
The result format is in the following example.
Examples
Example 1:
Input:
Triangles table:
+----+----+----+
| A | B | C |
+----+----+----+
| 20 | 20 | 23 |
| 20 | 20 | 20 |
| 20 | 21 | 22 |
| 13 | 14 | 30 |
+----+----+----+
Output:
+----------------+
| triangle_type |
+----------------+
| Isosceles |
| Equilateral |
| Scalene |
| Not A Triangle |
+----------------+
Explanation:
- Values in the first row from an Isosceles triangle, because A = B.
- Values in the second row from an Equilateral triangle, because A = B = C.
- Values in the third row from an Scalene triangle, because A != B != C.
- Values in the fourth row cannot form a triangle, because the combined value of sides A and B is not larger than that of side C.
Solution
Method 1 – SQL Case Classification
Intuition
A triangle is valid if the sum of any two sides is greater than the third. Once validity is checked, we classify by the number of equal sides: three (Equilateral), two (Isosceles), or none (Scalene).
Approach
- For each row, check if the three sides can form a triangle using the triangle inequality.
- If not, output 'Not A Triangle'.
- If all three sides are equal, output 'Equilateral'.
- If exactly two sides are equal, output 'Isosceles'.
- Otherwise, output 'Scalene'.
Code
MySQL
SELECT
CASE
WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END AS triangle_type
FROM Triangles;
PostgreSQL
SELECT
CASE
WHEN A + B <= C OR A + C <= B OR B + C <= A THEN 'Not A Triangle'
WHEN A = B AND B = C THEN 'Equilateral'
WHEN A = B OR B = C OR A = C THEN 'Isosceles'
ELSE 'Scalene'
END AS triangle_type
FROM Triangles;
Python (pandas)
class Solution:
def classify_triangles(self, df):
def classify(row):
a, b, c = row['A'], row['B'], row['C']
if a + b <= c or a + c <= b or b + c <= a:
return 'Not A Triangle'
if a == b == c:
return 'Equilateral'
if a == b or b == c or a == c:
return 'Isosceles'
return 'Scalene'
df['triangle_type'] = df.apply(classify, axis=1)
return df[['triangle_type']]
Complexity
- ⏰ Time complexity: O(n), where n is the number of triangles.
- 🧺 Space complexity: O(1) (excluding input/output).