Triangle Judgement — LeetCode 610 Python Solution
EasyDatabase
- Problem
- #610
- Reading time
- 3 min
- Source
- leetcode.com
The problem
For every row, decide whether the three segment lengths can form a triangle and report the three lengths together with Yes or No. The Triangle table has one row per triple: x, y and z (int, the three segment lengths), with (x, y, z) as the primary key.
Example
Triangle table: | x | y | z | | -- | -- | -- | | 13 | 15 | 30 | | 10 | 20 | 15 | | 5 | 5 | 5 | | 7 | 2 | 4 | Result: | x | y | z | triangle | | -- | -- | -- | -------- | | 13 | 15 | 30 | No | | 10 | 20 | 15 | Yes | | 5 | 5 | 5 | Yes | | 7 | 2 | 4 | No | A triple works only when every pair of sides is longer than the third, which fails for 13, 15 and 30 because 13 plus 15 is under 30, and fails again for 7, 2 and 4.
Python solution
Python
import pandas as pd
def triangle_judgement(triangle: pd.DataFrame) -> pd.DataFrame:
df = triangle.copy()
valid = (
(df['x'] + df['y'] > df['z'])
& (df['x'] + df['z'] > df['y'])
& (df['y'] + df['z'] > df['x'])
)
df['triangle'] = valid.map({True: 'Yes', False: 'No'})
return df[['x', 'y', 'z', 'triangle']]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 610. Triangle Judgement?
- LeetCode 610. Triangle Judgement is rated Easy on LeetCode.
- What topics does LeetCode 610. Triangle Judgement cover?
- LeetCode 610. Triangle Judgement is tagged Database on LeetCode.