algoadvance

Leetcode 3024. Type of Triangle

Problem Statement

You are given the lengths of three sides of a triangle. Determine the type of triangle those sides form. The possible types of triangles are:

  1. Equilateral triangle: All three sides are equal.
  2. Isosceles triangle: Exactly two sides are equal.
  3. Scalene triangle: All three sides are different.
  4. Not a triangle: The sides do not form a valid triangle.

The input will be three positive integers, a, b, and c, representing the lengths of the sides of the triangle.

Clarifying Questions

  1. Are the sides guaranteed to be positive integers?
  2. Should we handle the case where the inputs do not form a valid triangle?
  3. Do we need to take any constraints into account, such as maximum input size?

Assuming the answers are:

  1. Yes, the sides are guaranteed to be positive integers.
  2. Yes, we must consider if the inputs can form a valid triangle.
  3. There is no specific constraint on the input size other than being reasonable for standard integer ranges.

Strategy

  1. Check Validity: For three lengths to form a triangle, they must satisfy the triangle inequality theorem:
    • a + b > c
    • a + c > b
    • b + c > a

    If these conditions are not met, the sides do not form a triangle.

  2. Classify Triangle:
    • If all three sides are equal (a == b == c), then it’s an equilateral triangle.
    • If exactly two sides are equal (a == b, b == c, or a == c), then it’s an isosceles triangle.
    • If all sides are different (a != b, b != c, and a != c), then it’s a scalene triangle.

Code

#include <iostream>
using namespace std;

string typeOfTriangle(int a, int b, int c) {
    // First, check if it's a valid triangle
    if (a + b <= c || a + c <= b || b + c <= a) {
        return "Not a triangle";
    }
    
    // Then, determine the type of triangle
    if (a == b && b == c) {
        return "Equilateral triangle";
    } else if (a == b || b == c || a == c) {
        return "Isosceles triangle";
    } else {
        return "Scalene triangle";
    }
}

int main() {
    int a, b, c;
    cout << "Enter the sides of the triangle: ";
    cin >> a >> b >> c;

    string result = typeOfTriangle(a, b, c);
    cout << "The type of triangle is: " << result << endl;
    
    return 0;
}

Time Complexity

The time complexity of this code is O(1) because the operations involved (comparison and string return) are constant time operations. The space complexity is also O(1) since no additional space proportional to the input size is used.

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