Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Equal side lengths determine a triangle's type only after the lengths are known to form a triangle. With positive sides, the sum of every pair must be strictly larger than the remaining side. Equality would produce a flat, invalid triangle.
Approach
Read the three lengths and test all three triangle inequalities. Return none if any pair sum is less than or equal to the other side.
For a valid triangle, first check whether all three sides are equal and return equilateral. Otherwise, if any pair is equal, return isosceles. If no pair is equal, return scalene. Checking the all-equal case first is important because it also satisfies the condition that some pair is equal. Exactly three sides are inspected, so sorting is unnecessary.
class Solution:
def triangleType(self, nums: List[int]) -> str:
a = nums[0]
b = nums[1]
c = nums[2]
if a + b <= c or b + c <= a or a + c <= b:
return 'none'
if a == b and b == c:
return 'equilateral'
if a == b or b == c or a == c:
return 'isosceles'
if a != b and b != c and a != c:
return 'scalene'Complexity analysis
Time: O(1) because exactly three side lengths are inspected. Auxiliary space: O(1).
