Facebook SQL Interview Questions – Leetcode 610 – Triangle Judgement

Problem Description –

A pupil Tim gets homework to identify whether three line segments could possibly form a triangle.

However, this assignment is very heavy because there are hundreds of records to calculate.

Could you help Tim by writing a query to judge whether these three sides can form a triangle, assuming table triangle holds the length of the three sides x, y and z.

Table – triangle

For the sample data above, your query should return the follow result:

Difficulty Level – Easy

Solution –

SELECT
    x,
    y,
    z,
    CASE WHEN x + y > z AND y + z > x AND z + x > y THEN 'Yes'
        ELSE 'No' END AS triangle
FROM triangle

For three segments to form a triangle, the sum of any two segments has to be larger than the third one. So, in the CASE statement we define three conditions with AND operation because all of the conditions needs to be true in order to form a triangle. If you add x and y for the second row it will be 30 which is greater than the value of z (15). And if you add y + z, it will be 35, which is greater than x(10) and if you add z + x, it will be 35, which is also greater than y(20). The second row satisfy all three conditions and hence form a triangle but the first row does not satify all the condition that is why it doesn’t form a triangle.

Leave a Reply