3024. Type of Triangle
Problem Description
You are given an array nums
containing exactly 3 integers (0-indexed) that represent potential side lengths of a triangle.
Your task is to determine what type of triangle can be formed using these three side lengths, or if no triangle can be formed at all.
The triangle types are defined as:
- Equilateral: All three sides have equal length
- Isosceles: Exactly two sides have equal length (the third side is different)
- Scalene: All three sides have different lengths
For three lengths to form a valid triangle, they must satisfy the triangle inequality theorem: the sum of any two sides must be greater than the third side.
Return a string indicating the triangle type:
"equilateral"
if all sides are equal"isosceles"
if exactly two sides are equal"scalene"
if all sides are different"none"
if the three lengths cannot form a valid triangle
For example:
nums = [3, 3, 3]
would return"equilateral"
nums = [3, 4, 3]
would return"isosceles"
nums = [3, 4, 5]
would return"scalene"
nums = [1, 1, 3]
would return"none"
(since 1 + 1 = 2 is not greater than 3)
Intuition
The key insight is that by sorting the array first, we can simplify both the triangle validity check and the type classification.
When we sort the three sides as nums[0] <= nums[1] <= nums[2]
, checking if they can form a valid triangle becomes much simpler. Instead of checking all three triangle inequality conditions:
nums[0] + nums[1] > nums[2]
nums[0] + nums[2] > nums[1]
nums[1] + nums[2] > nums[0]
We only need to check one condition: nums[0] + nums[1] > nums[2]
. Why? Because after sorting, nums[2]
is the largest side. If the sum of the two smaller sides is greater than the largest side, the other two conditions are automatically satisfied (since the sum of any side with the largest side will definitely be greater than the remaining smaller side).
Once we know a valid triangle can be formed, classifying its type becomes straightforward with the sorted array:
- If the smallest equals the largest (
nums[0] == nums[2]
), then all three must be equal → equilateral - If either the first two are equal (
nums[0] == nums[1]
) or the last two are equal (nums[1] == nums[2]
), then we have exactly two equal sides → isosceles - Otherwise, all three sides are different → scalene
Sorting transforms a potentially complex comparison problem into a clean, linear sequence of checks, making the solution both elegant and efficient.
Solution Approach
Following the intuition, let's implement the solution step by step:
Step 1: Sort the array
nums.sort()
After sorting, we have nums[0] <= nums[1] <= nums[2]
, where nums[0]
is the smallest side, nums[1]
is the middle side, and nums[2]
is the largest side.
Step 2: Check triangle validity
if nums[0] + nums[1] <= nums[2]: return "none"
We only need to check if the sum of the two smaller sides is greater than the largest side. If nums[0] + nums[1] <= nums[2]
, the three lengths cannot form a valid triangle, so we return "none"
.
Step 3: Classify the triangle type
Once we know a valid triangle can be formed, we check the equality relationships between sides:
if nums[0] == nums[2]: return "equilateral"
If the smallest side equals the largest side, then all three sides must be equal (since nums[0] <= nums[1] <= nums[2]
), making it an equilateral triangle.
if nums[0] == nums[1] or nums[1] == nums[2]: return "isosceles"
If either the first two sides are equal or the last two sides are equal, we have exactly two equal sides, making it an isosceles triangle.
return "scalene"
If none of the above conditions are met, all three sides must be different, making it a scalene triangle.
Time Complexity: O(1)
- Sorting an array of fixed size 3 is constant time.
Space Complexity: O(1)
- We sort in-place and use no extra space.
Ready to land your dream job?
Unlock your dream job with a 5-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through the solution with nums = [5, 3, 4]
:
Step 1: Sort the array
- Original:
[5, 3, 4]
- After sorting:
[3, 4, 5]
- Now we have smallest = 3, middle = 4, largest = 5
Step 2: Check triangle validity
- Check if
nums[0] + nums[1] > nums[2]
- Is
3 + 4 > 5
? - Yes,
7 > 5
is true, so we can form a valid triangle
Step 3: Classify the triangle type
- Check if
nums[0] == nums[2]
: Is3 == 5
? No - Check if
nums[0] == nums[1]
: Is3 == 4
? No - Check if
nums[1] == nums[2]
: Is4 == 5
? No - Since no sides are equal, return
"scalene"
Let's trace through another example where no triangle can be formed: nums = [1, 1, 3]
:
Step 1: Sort the array
- Already sorted:
[1, 1, 3]
Step 2: Check triangle validity
- Check if
nums[0] + nums[1] > nums[2]
- Is
1 + 1 > 3
? - No,
2 > 3
is false - Return
"none"
immediately
The sorting step is crucial because it allows us to:
- Only check one inequality instead of three
- Easily identify the triangle type by checking adjacent elements in the sorted array
Solution Implementation
1from typing import List
2
3
4class Solution:
5 def triangleType(self, nums: List[int]) -> str:
6 """
7 Determine the type of triangle based on three side lengths.
8
9 Args:
10 nums: List of three integers representing the sides of a triangle
11
12 Returns:
13 String indicating triangle type: "none", "equilateral", "isosceles", or "scalene"
14 """
15 # Sort the sides in ascending order for easier comparison
16 nums.sort()
17
18 # Check triangle inequality: sum of two smaller sides must be greater than the largest side
19 if nums[0] + nums[1] <= nums[2]:
20 return "none"
21
22 # Check if all three sides are equal (equilateral triangle)
23 if nums[0] == nums[2]:
24 return "equilateral"
25
26 # Check if exactly two sides are equal (isosceles triangle)
27 if nums[0] == nums[1] or nums[1] == nums[2]:
28 return "isosceles"
29
30 # If no sides are equal, it's a scalene triangle
31 return "scalene"
32
1class Solution {
2 /**
3 * Determines the type of triangle formed by three sides.
4 * @param nums Array containing three side lengths
5 * @return Triangle type: "none", "equilateral", "isosceles", or "scalene"
6 */
7 public String triangleType(int[] nums) {
8 // Sort the array to ensure nums[0] <= nums[1] <= nums[2]
9 Arrays.sort(nums);
10
11 // Check triangle inequality: sum of two smaller sides must be greater than the largest side
12 if (nums[0] + nums[1] <= nums[2]) {
13 return "none";
14 }
15
16 // Check for equilateral triangle: all three sides are equal
17 if (nums[0] == nums[2]) {
18 return "equilateral";
19 }
20
21 // Check for isosceles triangle: exactly two sides are equal
22 if (nums[0] == nums[1] || nums[1] == nums[2]) {
23 return "isosceles";
24 }
25
26 // If none of the above conditions are met, it's a scalene triangle
27 return "scalene";
28 }
29}
30
1class Solution {
2public:
3 string triangleType(vector<int>& nums) {
4 // Sort the three sides in ascending order for easier comparison
5 sort(nums.begin(), nums.end());
6
7 // Check triangle inequality: sum of two smaller sides must be greater than the largest side
8 // If not satisfied, it cannot form a valid triangle
9 if (nums[0] + nums[1] <= nums[2]) {
10 return "none";
11 }
12
13 // Check if all three sides are equal (equilateral triangle)
14 // Since array is sorted, we only need to compare first and last elements
15 if (nums[0] == nums[2]) {
16 return "equilateral";
17 }
18
19 // Check if exactly two sides are equal (isosceles triangle)
20 // After sorting, equal sides must be adjacent
21 if (nums[0] == nums[1] || nums[1] == nums[2]) {
22 return "isosceles";
23 }
24
25 // If none of the above conditions are met, all sides are different (scalene triangle)
26 return "scalene";
27 }
28};
29
1/**
2 * Determines the type of triangle formed by three given side lengths
3 * @param nums - Array of three numbers representing potential triangle sides
4 * @returns Type of triangle: 'none', 'equilateral', 'isosceles', or 'scalene'
5 */
6function triangleType(nums: number[]): string {
7 // Sort the sides in ascending order to simplify triangle inequality check
8 nums.sort((a: number, b: number) => a - b);
9
10 // Check triangle inequality: sum of two smaller sides must be greater than the largest side
11 if (nums[0] + nums[1] <= nums[2]) {
12 return 'none';
13 }
14
15 // Check if all three sides are equal (equilateral triangle)
16 if (nums[0] === nums[2]) {
17 return 'equilateral';
18 }
19
20 // Check if exactly two sides are equal (isosceles triangle)
21 if (nums[0] === nums[1] || nums[1] === nums[2]) {
22 return 'isosceles';
23 }
24
25 // If no sides are equal, it's a scalene triangle
26 return 'scalene';
27}
28
Time and Space Complexity
The time complexity is O(1)
. The sorting operation nums.sort()
typically has O(n log n)
complexity for general cases, but since the input array nums
has a fixed size of 3 elements (as it represents the three sides of a triangle), the sorting operation takes constant time. All other operations (comparisons and returns) are also constant time operations.
The space complexity is O(1)
. The sorting is done in-place, modifying the original array without requiring additional space proportional to the input size. Only a constant amount of extra space is used for the sorting algorithm's internal operations on the 3-element array.
Learn more about how to find time and space complexity quickly.
Common Pitfalls
Pitfall 1: Forgetting to Check All Triangle Inequality Conditions
The Problem:
A common mistake is assuming that checking only nums[0] + nums[1] > nums[2]
after sorting is sufficient. While this is mathematically correct for sorted arrays, developers sometimes write incomplete checks when not sorting first, leading to incorrect results.
Incorrect Implementation:
def triangleType(self, nums: List[int]) -> str:
# Wrong: Only checking one inequality without sorting
if nums[0] + nums[1] <= nums[2]:
return "none"
# ... rest of the logic
Why It Fails:
Without sorting, nums[2]
might not be the largest side. For example, with nums = [5, 3, 2]
, checking only 5 + 3 > 2
would pass, but 3 + 2 > 5
fails, so it's not a valid triangle.
Solution: Either sort the array first (as in the provided solution) or check all three inequalities:
# Option 1: Sort first (recommended) nums.sort() if nums[0] + nums[1] <= nums[2]: return "none" # Option 2: Check all three conditions if (nums[0] + nums[1] <= nums[2] or nums[0] + nums[2] <= nums[1] or nums[1] + nums[2] <= nums[0]): return "none"
Pitfall 2: Incorrect Classification of Isosceles Triangle
The Problem: Some developers mistakenly classify an equilateral triangle as isosceles since an equilateral triangle technically has "at least two equal sides."
Incorrect Implementation:
def triangleType(self, nums: List[int]) -> str:
nums.sort()
if nums[0] + nums[1] <= nums[2]:
return "none"
# Wrong: Checking isosceles before equilateral
if nums[0] == nums[1] or nums[1] == nums[2]:
return "isosceles" # This would incorrectly classify [3,3,3] as isosceles
if nums[0] == nums[2]:
return "equilateral" # This would never be reached
return "scalene"
Why It Fails:
The condition for isosceles would match an equilateral triangle (where all sides are equal), returning "isosceles" instead of "equilateral" for cases like [3, 3, 3]
.
Solution: Always check for equilateral first (most specific condition), then isosceles (less specific), then scalene (least specific):
# Correct order: most specific to least specific if nums[0] == nums[2]: # All three equal return "equilateral" if nums[0] == nums[1] or nums[1] == nums[2]: # Exactly two equal return "isosceles" return "scalene" # All different
Pitfall 3: Not Handling Edge Cases with Zero or Negative Values
The Problem: While the problem might specify positive integers, developers sometimes forget that triangles cannot have sides with zero or negative lengths.
Incorrect Assumption:
def triangleType(self, nums: List[int]) -> str:
nums.sort()
# Missing validation for non-positive values
if nums[0] + nums[1] <= nums[2]:
return "none"
# ... rest of the logic
Why It Fails:
If nums = [0, 3, 3]
or nums = [-1, 2, 2]
, the code might not properly identify these as invalid triangles if the inequality check happens to pass.
Solution: Add explicit validation for non-positive values:
def triangleType(self, nums: List[int]) -> str:
# Check for non-positive values first
if any(side <= 0 for side in nums):
return "none"
nums.sort()
if nums[0] + nums[1] <= nums[2]:
return "none"
# ... rest of the logic
Note: This validation might not be necessary if the problem constraints guarantee positive values, but it's good defensive programming practice.
Which of the following problems can be solved with backtracking (select multiple)
Recommended Readings
Math for Technical Interviews How much math do I need to know for technical interviews The short answer is about high school level math Computer science is often associated with math and some universities even place their computer science department under the math faculty However the reality is that you
Sorting Summary Comparisons We presented quite a few sorting algorithms and it is essential to know the advantages and disadvantages of each one The basic algorithms are easy to visualize and easy to learn for beginner programmers because of their simplicity As such they will suffice if you don't know any advanced
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Want a Structured Path to Master System Design Too? Don’t Miss This!