EasyNo. 0610

Triangle Judgement — LeetCode 610 Python Solution

Topics
Database
Reading time
3 min

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

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

PythonSolution
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

Related problems
No.ProblemDifficulty
0120TriangleMedium
0608Tree NodeMedium
0607Sales PersonEasy
0602Friend Requests II: Who Has the Most FriendsMedium
0601Human Traffic of StadiumHard
0619Biggest Single NumberEasy

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.