Problem 3024

Abstract / Summary

Given three side lengths determine if they form an equilateral isosceles or scalene triangle or cannot form a triangle

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 3024.py

class Solution:
    def triangleType(self, nums: List[int]) -> str:
        a, b, c = nums
        if a + b <= c or a + c <= b or b + c <= a:
            return "none" # invalid triangle

        size = len(set(nums))
        if size == 1:
            return "equilateral"
        if size == 2:
            return "isosceles"
        else:
            return "scalene"
13 lines | 382 bytes | submitted March 16, 2024 | GitHub   8% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 45% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
  • Sorting
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a single method triangleType. The method receives a list of three integers representing side lengths of a triangle and returns a string describing the triangle’s classification: "equilateral", "isosceles", "scalene" or "none" when the sides cannot form a valid triangle. The logic proceeds in three distinct phases: unpacking the input, validating the triangle inequality, and determining the type based on the count of unique side lengths.

Key Steps

The first step extracts the three side lengths from the input list. By assigning the three elements directly to variables a, b, and c, the code makes the subsequent checks more readable.

a, b, c = nums

The second step validates whether the three lengths satisfy the triangle inequality. The condition checks each pair of sides to ensure their sum exceeds the remaining side. If any of the three checks fails, the method returns "none" to indicate that the sides cannot constitute a triangle.

if a + b <= c or a + c <= b or b + c <= a:
    return "none"  # invalid triangle

The third step classifies the triangle by counting how many distinct side lengths are present. The set conversion removes duplicates, and the size of the resulting set determines the classification.

size = len(set(nums))
if size == 1:
    return "equilateral"
if size == 2:
    return "isosceles"
else:
    return "scalene"

Edge Cases Handled

The validation block explicitly handles degenerate cases where the sum of two sides equals the third side. By using the <= operator, the code treats both equality and strict inequality violations as invalid, covering scenarios such as zero-length sides or collinear points that would otherwise satisfy a non-strict inequality. This ensures that only proper triangles are classified.

When all three side lengths are identical, the set conversion yields a single element, leading to the "equilateral" result. The case where exactly two sides are equal results in a set size of two, correctly mapping to "isosceles". The final else clause captures the situation where all three sides differ, delivering the "scalene" classification. These branches collectively address every possible combination of side equality.

Performance Optimizations

The method operates in constant time relative to the size of the input because the list always contains exactly three elements. Unpacking the list into three variables avoids repeated indexing, which can be marginally faster than accessing elements via nums[0], nums[1], and nums[2]. The triangle inequality check combines all three necessary comparisons into a single conditional expression, preventing unnecessary branching.

Creating a set from a three-element list is an O(1) operation in practice, and the subsequent len call retrieves the count of unique values without additional iteration. By using the size of the set directly to drive the classification logic, the code eliminates the need for multiple equality checks between individual side pairs, reducing the overall number of comparisons. This streamlined approach yields a concise and efficient implementation for the fixed-size input scenario.

written by openai gpt

ELI5 - Simplified Explanation

Imagine three sticks of different lengths that you want to put together to make a triangle shape. The computer looks at the lengths of these three sticks. First, it checks if the sticks can actually join up to form a proper shape. If the two smaller sticks are too short to reach across the longest one, the shape cannot be closed, so the computer says none.

If the sticks work, the computer looks at their lengths to see if any are the same. If all three sticks are exactly the same size, it calls the triangle equilateral, which means all sides are equal. If just two sticks match and the third one is different, it calls that shape isosceles. Finally, if all three sticks have different lengths so that none of them match each other, it calls the triangle scalene.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.41 | σ = 1.37

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Java C++ Python TS
WalkCCC Java C++ Python
leetcode.ca Java C++ C# Go Python TS
Progiez Java C++ Python
github charles-wangkai Java
fsq C++
JoshCrozier JS
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
Progiez C++, Java, Python
charles-wangkai Java
fsq C++
JoshCrozier JavaScript
19 links | 7 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

1 medium
2 solutions   March 16, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality