#610
Triangle Judgement
EasyDatabaseTriangle InequalityConditional Logic
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is essentially the same as the brute force approach, as we need to check the triangle inequality for each set of segments. However, we can optimize the query execution by ensuring we only select valid combinations directly.
⚙️
Algorithm
3 steps- 1Step 1: For each row in the Triangle table, extract the values of x, y, and z.
- 2Step 2: Use the triangle inequality conditions to filter valid triangles directly in the SQL query.
- 3Step 3: Return the results with the triangle validity.
solution.py1 lines
1SELECT x, y, z, CASE WHEN (x + y > z AND x + z > y AND y + z > x) THEN 'Yes' ELSE 'No' END AS triangle FROM Triangle;ℹ
Complexity note: The time complexity remains O(n) as we still check each row once, and the space complexity is O(1) since we are not using any additional data structures.
- 1The triangle inequality theorem is crucial for determining if three lengths can form a triangle.
- 2Checking each combination of lengths is necessary to ensure accuracy.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.