Type of Triangle — Easy Problem & Solution

nums holds the three side lengths of a candidate triangle. Return: "equilateral" if all three sides are equal; "isosceles" if exactly two are equal;…

  • Difficulty: Easy
  • Topics: Arrays, Math, Sorting
  • Asked at: Amazon, Google, Infosys
  • Time limit: 2 s
  • Memory limit: 256 MB
  • Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby

Problem statement

nums holds the three side lengths of a candidate triangle. Return:

  • "equilateral" if all three sides are equal;
  • "isosceles" if exactly two are equal;
  • "scalene" if all three differ;
  • "none" if the sides cannot form a triangle at all.

Example 1

Input: nums = [3,3,3]
Output: equilateral

Example 2

Input: nums = [3,4,5]
Output: scalene

Example 3

Input: nums = [1,1,3]
Output: none
Explanation: 1 + 1 is not greater than 3.

Constraints

  • nums.length == 3
  • 1 <= nums[i] <= 100

How to solve Type of Triangle

Sort the three sides. The triangle inequality then reduces to a + b > c for the sorted sides; if it fails the answer is "none". Otherwise classify by how many sides are equal.

Approach

  1. Sort the three values ascending.
  2. Return "none" if s[0] + s[1] <= s[2].
  3. Return "equilateral" if all three match, "isosceles" if one adjacent pair matches, else "scalene".

Why it works

Sorting collapses three triangle-inequality checks into one — the other two hold automatically once the longest side is identified. And the validity test must come first: [1,1,3] has two equal sides but is not a triangle, so classifying before checking would wrongly call it isosceles.

Complexity

  • Time — O(1)
  • Space — O(1)

Pitfalls

  • The inequality is strict: 1 + 2 = 3 is degenerate and counts as "none".
  • Validity is checked before the equal-sides classification.
  • After sorting, equality only needs to be tested between adjacent sides.

Reference solution

Python

from typing import List

def triangleType(nums: List[int]) -> str:
    s = sorted(nums)
    if s[0] + s[1] <= s[2]:
        return "none"
    if s[0] == s[1] == s[2]:
        return "equilateral"
    if s[0] == s[1] or s[1] == s[2]:
        return "isosceles"
    return "scalene"

JavaScript

var triangleType = function(nums) {
    var s = nums.slice();
    s.sort(function(a, b) { return a - b; });
    if (s[0] + s[1] <= s[2]) return "none";
    if (s[0] === s[1] && s[1] === s[2]) return "equilateral";
    if (s[0] === s[1] || s[1] === s[2]) return "isosceles";
    return "scalene";
};

Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.

All 667 arrays problems · the whole catalogue