DEV Community

Cover image for Triangle Judgement | LeetCode | MSSQL
Retiago Drago
Retiago Drago

Posted on

Triangle Judgement | LeetCode | MSSQL

The Problem

Consider a table named Triangle with the following structure:

Column Name Type
x int
y int
z int

The primary key for this table is (x, y, z), each row of which represents the lengths of three line segments. Your task is to create an SQL query that can determine for each row if the three line segments can form a triangle.

Here's an example for better understanding:

Example

Input

Triangle table:

x y z
13 15 30
10 20 15

Output

Result table:

x y z triangle
13 15 30 No
10 20 15 Yes

In the example above, the first row cannot form a triangle because the sum of any two sides of a triangle should be greater than the third side, i.e., x + y > z, x + z > y, and y + z > x. However, 13 + 15 is not greater than 30, hence the 'No' in the 'triangle' column. In contrast, the lengths in the second row can form a triangle since 10 + 20 > 15, 10 + 15 > 20, and 20 + 15 > 10.

The Solution

Here's a simple yet effective SQL query that leverages the concept of conditional logic (CASE...WHEN...THEN...ELSE) to determine if three lengths can form a triangle:

SELECT 
    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
Enter fullscreen mode Exit fullscreen mode

This query will output 'Yes' if the lengths can form a triangle, and 'No' otherwise. The beauty of this query lies in its simplicity and directness. It directly applies the triangle inequality theorem, which states that the sum of the lengths of any two sides of a triangle is greater than the length of the remaining side.

Interestingly, the same query had different execution times on two different submissions:

  • First submission: runtime 624ms, beating 18.82% of other SQL submissions. first
  • Second submission: runtime 396ms, beating 83.20% of other SQL submissions. second

This difference can be attributed to several factors including server load and performance at the time of query execution.

You can find the original problem at LeetCode.

Want to see more insightful solutions and tech-related content? Feel free to connect with me on my Beacons page.

ranggakd - Link in Bio & Creator Tools | Beacons

@ranggakd | center details summary summary Oh hello there I m a an Programmer AI Tech Writer Data Practitioner Statistics Math Addict Open Source Contributor Quantum Computing Enthusiast details center.

favicon beacons.ai

Top comments (0)