algoadvance

Leetcode 3024. Type of Triangle

Problem Statement

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:

  1. Equilateral - All three sides have equal length.
  2. Isosceles - Exactly two sides have equal length.
  3. Scalene - All three sides have different lengths.
  4. Not a triangle - The sides do not form a valid triangle.

A set of three sides (a, b, c) will form a valid triangle if:

Clarifying Questions

  1. Input Constraints:
    • Can the side lengths be zero or negative?
    • What is the range of the side lengths?
  2. Output:
    • Should the output be a specific string indicating the type of triangle?

Strategy

  1. Validation:
    • First, check if the given side lengths form a valid triangle using the triangle inequality theorem.
  2. Classification:
    • If valid, classify the triangle based on the side lengths:
      • If all three sides are equal, it’s an Equilateral triangle.
      • If exactly two sides are equal, it’s an Isosceles triangle.
      • If all three sides are different, it’s a Scalene triangle.
    • If not valid, return “Not a triangle”.

Code

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
    }
}

Time Complexity

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.

Summary

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.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI