You are given a 0-indexed integer array nums
of size 3
which can form the sides of a triangle.
Return a string representing the type of triangle that can be formed or "none"
if it cannot form a triangle.*
For example:
nums = [3,3,3]
should return "equilateral"
because all sides are equal.nums = [3,4,5]
should return "scalene"
because no sides are equal and 3 + 4 > 5, 3 + 5 > 4, and 4 + 5 > 3.nums = [1,2,5]
should return "none"
because 1 + 2 is not greater than 5, meaning a triangle cannot be formed.def triangleType(nums):
"""
Given a 0-indexed integer array nums of size 3 which can form the sides of a triangle.
A triangle is called equilateral if it has all sides of equal length.
A triangle is called isosceles if it has exactly two sides of equal length.
A triangle is called scalene if all its sides are of different lengths.
Return a string representing the type of triangle that can be formed or "none" if it cannot form a triangle.
"""
a, b, c = nums
# Check if it can form a triangle
if a + b <= c or a + c <= b or b + c <= a:
return "none"
# Check for equilateral
if a == b == c:
return "equilateral"
# Check for isosceles
if a == b or a == c or b == c:
return "isosceles"
# Otherwise, it's scalene
return "scalene"
# Example Usage
nums1 = [3, 3, 3]
print(triangleType(nums1)) # Output: equilateral
nums2 = [3, 4, 5]
print(triangleType(nums2)) # Output: scalene
nums3 = [5, 4, 5]
print(triangleType(nums3)) # Output: isosceles
nums4 = [1, 2, 5]
print(triangleType(nums4)) # Output: none
a == b == c
), it's an equilateral triangle, and the function should return "equilateral".a == b or a == c or b == c
), it's an isosceles triangle, and the function should return "isosceles".The function performs a fixed number of comparisons and assignments, regardless of the input values. Therefore, the time complexity is O(1), which means it has constant time complexity.
The function uses a fixed amount of extra space to store the variables a
, b
, and c
. The space used does not depend on the input values. Therefore, the space complexity is O(1), which means it has constant space complexity.
1 <= nums[i] <= 100
. If the input constraints allowed zero or negative lengths, additional checks would be needed at the beginning of the function to ensure all sides are positive.1 <= nums[i] <= 100
ensures that the sums will not overflow.abs(a - b) < tolerance
). However, this problem deals only with integers.