610. Triangle Judgement
Model: qwen2.5-coder:14b
Topics:
FAANG asked: 1
Acceptance rate: 68.9%
Problem Breakdown
The problem requires determining whether three given side lengths can form a triangle. The inputs are three integers representing the lengths of the sides. The output should be a boolean indicating whether these sides can form a valid triangle. A key constraint is that for any three sides to form a triangle, the sum of the lengths of any two sides must be greater than the length of the third side (Triangle Inequality Theorem). Edge cases include zero or negative side lengths, and identical side lengths.
Intuition
The brute-force approach would involve checking all possible combinations of the three sides to see if they satisfy the triangle inequality theorem. However, this is unnecessary because we only need to check three conditions: a + b > c, a + c > b, and b + c > a. This approach has a constant time complexity O(1) since it involves a fixed number of operations.
The key insight here is that we can directly apply the triangle inequality theorem to determine if the sides form a valid triangle without needing to sort or rearrange the sides.
Approach
To solve this problem, we will implement a function that takes three integers as input and returns a boolean. The steps are straightforward:
- Check if any of the side lengths are less than or equal to zero. If so, return False because a triangle cannot have non-positive side lengths.
- Apply the triangle inequality theorem by checking the three conditions: a + b > c, a + c > b, and b + c > a.
- Return True if all conditions are satisfied; otherwise, return False.
Complexity Analysis
- Time Complexity: O(1) - The solution involves a constant number of operations regardless of the input size.
- Space Complexity: O(1) - No additional space is required beyond the input variables.
Solution
def can_form_triangle(a, b, c):
# Check for non-positive side lengths
if a <= 0 or b <= 0 or c <= 0:
return False
# Apply triangle inequality theorem
if (a + b > c) and (a + c > b) and (b + c > a):
return True
else:
return False
Edge Cases Handled
- Zero or Negative Side Lengths: The function checks for non-positive side lengths and returns False immediately, as such sides cannot form a triangle.
- Identical Side Lengths: While identical side lengths can form an equilateral triangle, the function will correctly identify them as valid triangles by satisfying the triangle inequality conditions.