EasyNo. 0610
Triangle Judgement — LeetCode 610 Python Solution
- Topics
- Database
- 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
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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0120 | Triangle | Medium |
| 0608 | Tree Node | Medium |
| 0607 | Sales Person | Easy |
| 0602 | Friend Requests II: Who Has the Most Friends | Medium |
| 0601 | Human Traffic of Stadium | Hard |
| 0619 | Biggest Single Number | Easy |
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.