We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Type of Triangle

Number: 3321

Difficulty: Easy

Paid? No

Companies: IBM


Problem Description

Given a 0-indexed integer array nums of size 3 representing the sides of a potential triangle, determine the type of triangle that can be formed. Return "equilateral" if all sides are equal, "isosceles" if exactly two sides are equal, "scalene" if all sides are different, and "none" if the triangle conditions are not met.


Key Insights

  • The triangle inequality theorem must be satisfied: the sum of any two sides should be greater than the third.
  • Check if all sides are equal for an equilateral triangle.
  • For an isosceles triangle, exactly two sides must match.
  • For a scalene triangle, all three sides must be of different lengths.
  • Sorting the array can simplify the triangle inequality check.

Space and Time Complexity

Time Complexity: O(1) – as the input size is fixed with 3 elements. Space Complexity: O(1) – only a constant amount of extra space is used.


Solution

The solution uses a simple conditional checking strategy. First, verify the triangle inequality by ensuring that the sum of the two smallest sides is greater than the largest side (can be efficiently done by sorting the array). Once the triangle validity is confirmed, determine the triangle type by comparing the sides:

  • Use equality checks to determine if all three sides are equal (equilateral).
  • Then, check if exactly two sides are equal (isosceles).
  • If neither of those conditions is met, then the triangle must be scalene. Data structures used include arrays and the algorithmic approach is to use sorting (for convenience) and simple conditional checks.

Code Solutions

# Function to determine the type of triangle
def triangleType(nums):
    # Sort the numbers to simplify triangle validity check (smallest to largest).
    nums.sort()
    a, b, c = nums[0], nums[1], nums[2]
    
    # Check if the three sides can form a triangle using triangle inequality: a + b > c.
    if a + b <= c:
        return "none"
    
    # Check if all sides are equal.
    if a == b and b == c:
        return "equilateral"
    
    # Check if exactly two sides are equal.
    if a == b or b == c or a == c:
        return "isosceles"
    
    # If neither of the above, then it must be a scalene triangle.
    return "scalene"

# Example usage:
print(triangleType([3, 4, 5]))  # Expected output: "scalene"
← Back to All Questions