Leetcode 3024. Type of Triangle
Given three integers representing the lengths of the sides of a triangle, determine the type of triangle they form. The possible types of triangles are:
A set of three sides (a, b, c) will form a valid triangle if:
public class TriangleType {
public static String determineTriangleType(int a, int b, int c) {
// Check for valid triangle using triangle inequality theorem
if (a + b <= c || b + c <= a || a + c <= b) {
return "Not a triangle";
}
// Determine type of triangle
if (a == b && b == c) {
return "Equilateral";
} else if (a == b || b == c || a == c) {
return "Isosceles";
} else {
return "Scalene";
}
}
public static void main(String[] args) {
// Test cases
System.out.println(determineTriangleType(3, 3, 3)); // Equilateral
System.out.println(determineTriangleType(3, 4, 4)); // Isosceles
System.out.println(determineTriangleType(3, 4, 5)); // Scalene
System.out.println(determineTriangleType(1, 1, 2)); // Not a triangle
}
}
The time complexity of this solution is ( O(1) ) since the operations performed (comparisons and equality checks) are done in constant time. There are no loops or recursive calls.
This solution succinctly determines the type of a triangle based on its side lengths and efficiently ensures that the side lengths form a valid triangle before classification. Make sure to handle edge cases such as non-positive side lengths if necessary.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?