Leetcode 3024. Type of Triangle
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:
The input will be three positive integers, a
, b
, and c
, representing the lengths of the sides of the triangle.
Assuming the answers are:
a + b > c
a + c > b
b + c > a
If these conditions are not met, the sides do not form a triangle.
a == b == c
), then it’s an equilateral triangle.a == b
, b == c
, or a == c
), then it’s an isosceles triangle.a != b
, b != c
, and a != c
), then it’s a scalene triangle.#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;
}
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.
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?