Angles of a Triangle Problem
Description
LeetCode Problem 3899.
You are given a positive integer array sides of length 3.
Determine if there exists a triangle with positive area whose three side lengths are given by the elements of sides.
If such a triangle exists, return an array of three floating-point numbers representing its internal angles (in degrees), sorted in non-decreasing order. Otherwise, return an empty array.
Answers within 10^(-5) of the actual answer will be accepted.
Example 1:
Input: sides = [3,4,5]
Output: [36.86990,53.13010,90.00000]
Explanation:
You can form a right-angled triangle with side lengths 3, 4, and 5. The internal angles of this triangle are approximately 36.869897646, 53.130102354, and 90 degrees respectively.
Example 2:
Input: sides = [2,4,2]
Output: []
Explanation:
You cannot form a triangle with positive area using side lengths 2, 4, and 2.
Constraints:
sides.length == 31 <= sides[i] <= 1000
Solution
Approach: Sorting + Math
Sort the sides so that a <= b <= c. By the triangle inequality, a triangle with positive area exists only when a + b > c; otherwise return an empty array.
Otherwise the law of cosines gives the angles opposite to the sides:
cos A = (b^2 + c^2 - a^2) / (2bc)cos B = (a^2 + c^2 - b^2) / (2ac)
Take acos of each and convert to degrees. The third angle is C = 180 - A - B. Because a <= b <= c, the angles come out already sorted as A <= B <= C.
Complexity:
- Time complexity:
O(1). - Space complexity:
O(1).
from math import acos, degrees
class Solution:
def internalAngles(self, sides: List[int]) -> List[float]:
sides.sort()
a, b, c = sides
if a + b <= c:
return []
A = degrees(acos((b**2 + c**2 - a**2) / (2 * b * c)))
B = degrees(acos((a**2 + c**2 - b**2) / (2 * a * c)))
C = 180 - A - B
return [A, B, C]