Talentd
FleetCode
Make and follow sheets.Sign in

Triangle Judgement solution and explanation

EasyDatabase5 min read75.4% acceptanceUpdated 9 Apr 2026
Triangle Judgement | Leetcode 610 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 4:52 · 7K viewsWatch on YouTube
8 more videos on this problem
  1. Triangle Judgement | Leetcode 610 | Crack SQL Interviews in 50 Qs #mysql #leetcodeLearn With Chirag · 4:52 · 7K views
  2. LeetCode 610: Triangle Judgement [SQL]Frederik Müller · 9:29 · 3K views
  3. LeetCode 610 - Triangle Judgement (Python and SQL) [Easy]Ryan & Matt Data Science · 7:02 · 289 views
  4. 610. Triangle Judgement (LeetCode, SQL)hakunamatasq · 3:46 · 94 views
  5. SQL Tutorial: Triangle Judgement - Deciphering LeetCode Problem 610vanAmsen · 3:10 · 80 views
  6. 610. Triangle Judgement | LeetCode | Sql | TOP 50 QUESTIONS | #sql #leetcodedailychallengeSheCodes · 4:40 · 66 views
  7. Leetcode 610. Triangle Judgement | SQL Solution ExplainedDevOps Codex · 7:47 · 65 views
  8. Leetcode SQL 50 | 610. Triangle Judgement SolutionTrang Ng · 4:23 · 62 views
  9. Leetcode 610 | Triangle Judgement | Top 50 SQL | SQL Interview Question You MUST KnowAlgoChat · 7:49 · 56 views

The problem

Table: Triangle

+-------------+------+
| Column Name | Type |
+-------------+------+
| x           | int  |
| y           | int  |
| z           | int  |
+-------------+------+
In SQL, (x, y, z) is the primary key column for this table.
Each row of this table contains the lengths of three line segments.

Report for every three line segments whether they can form a triangle.

Return the result table in any order.

The result format is in the following example.

Example 1:

Input: 
Triangle table:
+----+----+----+
| x  | y  | z  |
+----+----+----+
| 13 | 15 | 30 |
| 10 | 20 | 15 |
+----+----+----+
Output: 
+----+----+----+----------+
| x  | y  | z  | triangle |
+----+----+----+----------+
| 13 | 15 | 30 | No       |
| 10 | 20 | 15 | Yes      |
+----+----+----+----------+

Approach overview

Problem Overview: Each row contains three side lengths x, y, and z. The task is to determine whether these three values can form a valid triangle and return Yes or No for every row.

A triangle is valid only when the triangle inequality holds: the sum of any two sides must be greater than the third side. If any of these conditions fail, the sides cannot form a triangle.

Approach 1: Direct Triangle Inequality Check (O(n) time, O(1) space)

The most direct solution applies the triangle inequality rule directly inside a SQL query. For each row, check whether x + y > z, x + z > y, and y + z > x. If all three conditions hold, return Yes; otherwise return No. In SQL this is usually implemented with a CASE WHEN expression that evaluates the three comparisons and outputs the result.

The database engine simply scans each row once and performs constant-time arithmetic comparisons. No joins, sorting, or extra structures are required. This makes the solution both efficient and easy to read. The approach works well for large tables because it performs a straightforward row-by-row evaluation with O(n) time complexity and O(1) additional space.

This method is the most common solution in database interview problems because it demonstrates that you understand how to express conditional logic directly in SQL using CASE and boolean expressions.

Approach 2: Pre-sorting Approach for Inequality Checks (O(n) time, O(1) space)

This approach relies on a mathematical observation. If the three sides are sorted so that a ≤ b ≤ c, only one condition needs to be checked: a + b > c. When the two smaller sides sum to more than the largest side, the other triangle inequalities automatically hold.

In practice, you conceptually reorder the values and then test the single inequality. Some implementations compute the smallest, middle, and largest values using SQL functions such as LEAST() and GREATEST(), or equivalent logic. After ordering the values, the query checks whether the sum of the two smallest sides exceeds the largest side.

This reduces the number of logical checks and highlights the mathematical property behind the triangle rule. The runtime remains O(n) because each row still requires a constant number of operations. The technique is often discussed in problems related to math reasoning and conditional evaluation in SQL.

Recommended for interviews: The direct triangle inequality check is what most interviewers expect. It clearly shows that you know the triangle property and can translate it into SQL logic using CASE WHEN. Mentioning the sorted-side observation demonstrates deeper mathematical reasoning, but the direct check is usually preferred for clarity and simplicity.

Approach 1: Approach 1: Direct Triangle Inequality Check

To determine whether three segments can form a triangle, we can directly apply the triangle inequality theorem. For segments with lengths x, y, and z to form a triangle, the following conditions must be met:

  • x + y > z
  • x + z > y
  • y + z > x

If all three conditions are satisfied, then the segments can form a triangle.

def check_triangle(x, y, z):
    result = "Yes" if (x + y > z and x + z > y and y + z > x) else "No"
    print(f"{x} {y} {z} {result}")

triangles = [(13, 15, 30), (10, 20, 15)]
for sides in triangles:
    check_triangle(*sides)
public class TriangleCheck {
    public static void checkTriangle(int x, int y, int z) {
        System.out.print(x + " " + y + " " + z + " ");
        if (x + y > z && x + z > y && y + z > x) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }

    public static void main(String[] args) {
        int[][] triangles = {{13, 15, 30}, {10, 20, 15}};
        for (int[] t : triangles) {
            checkTriangle(t[0], t[1], t[2]);
        }
    }
}
#include <iostream>
using namespace std;

void checkTriangle(int x, int y, int z) {
    cout << x << " " << y << " " << z << " ";
    if (x + y > z && x + z > y && y + z > x) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}

int main() {
    int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
    int n = sizeof(triangles) / sizeof(triangles[0]);
    
    for (int i = 0; i < n; i++) {
        checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
    }

    return 0;
}
function checkTriangle(x, y, z) {
    let result = (x + y > z && x + z > y && y + z > x) ? 'Yes' : 'No';
    console.log(`${x} ${y} ${z} ${result}`);
}

let triangles = [[13, 15, 30], [10, 20, 15]];
triangles.forEach(triangle => checkTriangle(...triangle));
#include <stdio.h>

void checkTriangle(int x, int y, int z) {
    if (x + y > z && x + z > y && y + z > x) {
        printf("%d %d %d Yes\n", x, y, z);
    } else {
        printf("%d %d %d No\n", x, y, z);
    }
}

int main() {
    int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
    int n = sizeof(triangles) / sizeof(triangles[0]);
    
    for (int i = 0; i < n; i++) {
        checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
    }

    return 0;
}
using System;

class TriangleCheck {
    static void CheckTriangle(int x, int y, int z) {
        string result = (x + y > z && x + z > y && y + z > x) ? "Yes" : "No";
        Console.WriteLine($"{x} {y} {z} {result}");
    }

    static void Main() {
        int[][] triangles = new int[][] {new int[] {13, 15, 30}, new int[] {10, 20, 15}};
        foreach (var sides in triangles) {
            CheckTriangle(sides[0], sides[1], sides[2]);
        }
    }
}

This Python script defines check_triangle, which prints whether three sides can form a triangle by applying the triangle inequality conditions, iterating over a list of side lengths.

Complexity

Time Complexity: O(1) for each evaluation.
Space Complexity: O(1).

Try this approach in the editor

Approach 2: Approach 2: Pre-sorting Approach for Inequality Checks

In this approach, we first sort the three sides so that we only need to check one inequality condition instead of three. Given sides x, y, and z, sort them to be a ≤ b ≤ c. Then check: a + b > c.

Sorting reduces the number of comparisons and handles the integer sides efficiently when checking validity of the triangle.

def check_triangle(x, y, z):
    sides = sorted([x, y, z])
    result = "Yes" if (sides[0] + sides[1] > sides[2]) else "No"
    print(f"{x} {y} {z} {result}")

triangles = [(13, 15, 30), (10, 20, 15)]
for sides in triangles:
    check_triangle(*sides)
import java.util.Arrays;

public class TriangleCheck {
    public static void checkTriangle(int x, int y, int z) {
        int[] sides = {x, y, z};
        Arrays.sort(sides);
        System.out.print(x + " " + y + " " + z + " ");
        if (sides[0] + sides[1] > sides[2]) {
            System.out.println("Yes");
        } else {
            System.out.println("No");
        }
    }

    public static void main(String[] args) {
        int[][] triangles = {{13, 15, 30}, {10, 20, 15}};
        for (int[] t : triangles) {
            checkTriangle(t[0], t[1], t[2]);
        }
    }
}
#include <iostream>
#include <algorithm>
using namespace std;

void checkTriangle(int x, int y, int z) {
    int sides[] = {x, y, z};
    sort(sides, sides + 3);
    cout << x << " " << y << " " << z << " ";
    if (sides[0] + sides[1] > sides[2]) {
        cout << "Yes" << endl;
    } else {
        cout << "No" << endl;
    }
}

int main() {
    int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
    int n = sizeof(triangles) / sizeof(triangles[0]);
    
    for (int i = 0; i < n; i++) {
        checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
    }

    return 0;
}
function checkTriangle(x, y, z) {
    let sides = [x, y, z];
    sides.sort((a, b) => a - b);
    let result = (sides[0] + sides[1] > sides[2]) ? 'Yes' : 'No';
    console.log(`${x} ${y} ${z} ${result}`);
}

let triangles = [[13, 15, 30], [10, 20, 15]];
triangles.forEach(triangle => checkTriangle(...triangle));
#include <stdio.h>

void sort(int *a, int *b, int *c) {
    if (*a > *b) { int t = *a; *a = *b; *b = t; }
    if (*a > *c) { int t = *a; *a = *c; *c = t; }
    if (*b > *c) { int t = *b; *b = *c; *c = t; }
}

void checkTriangle(int x, int y, int z) {
    sort(&x, &y, &z);
    if (x + y > z) {
        printf("%d %d %d Yes\n", x, y, z);
    } else {
        printf("%d %d %d No\n", x, y, z);
    }
}

int main() {
    int triangles[][3] = {{13, 15, 30}, {10, 20, 15}};
    int n = sizeof(triangles) / sizeof(triangles[0]);
    
    for (int i = 0; i < n; i++) {
        checkTriangle(triangles[i][0], triangles[i][1], triangles[i][2]);
    }

    return 0;
}
using System;

class TriangleCheck {
    static void CheckTriangle(int x, int y, int z) {
        int[] sides = new int[] {x, y, z};
        Array.Sort(sides);
        string result = (sides[0] + sides[1] > sides[2]) ? "Yes" : "No";
        Console.WriteLine($"{x} {y} {z} {result}");
    }

    static void Main() {
        int[][] triangles = new int[][] {new int[] {13, 15, 30}, new int[] {10, 20, 15}};
        foreach (var sides in triangles) {
            CheckTriangle(sides[0], sides[1], sides[2]);
        }
    }
}

This Python approach uses the sorted() function to order the sides before evaluating the critical summed condition for forming a triangle, thus reducing logical checks.

Complexity

Time Complexity: O(1) due to length sort and single condition check.
Space Complexity: O(1).

Try this approach in the editor

Approach 3: IF Statement + Triangle Inequality

The condition for whether three sides can form a triangle is that the sum of any two sides is greater than the third side. Therefore, we can use an IF statement to determine whether this condition is satisfied. If it is satisfied, we return Yes, otherwise we return No.

# Write your MySQL query statement below
SELECT
    *,
    IF(x + y > z AND x + z > y AND y + z > x, 'Yes', 'No') AS triangle
FROM Triangle;
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Direct Triangle Inequality Check

Time Complexity: O(1) for each evaluation.
Space Complexity: O(1).

Approach 2: Pre-sorting Approach for Inequality Checks

Time Complexity: O(1) due to length sort and single condition check.
Space Complexity: O(1).

IF Statement + Triangle Inequality–

Complexity analysis

ApproachTimeSpaceWhen to Use
Direct Triangle Inequality CheckO(n)O(1)Best general solution. Clear SQL CASE logic and minimal computation.
Pre-sorting Inequality CheckO(n)O(1)Useful when leveraging mathematical insight that only the two smallest sides need checking.

Frequently asked questions

Is Triangle Judgement easy or hard?

Triangle Judgement is considered an easy problem. It mainly tests whether you know the triangle inequality rule and can translate simple mathematical conditions into SQL using CASE expressions.

Triangle Judgement Python/Java solution

In Python, Java, or C++, the logic is the same as the SQL version: check three inequalities between the sides. If x + y > z, x + z > y, and y + z > x all hold, return true or 'Yes'; otherwise return false or 'No'. The algorithm runs in O(1) time for a single set of sides.

How to solve Triangle Judgement in O(n)?

Scan each row and apply the triangle inequality rule directly. Use a CASE WHEN statement to check whether x + y > z AND x + z > y AND y + z > x. If all conditions are true return 'Yes', otherwise return 'No'. This performs constant work per row, giving O(n) time.

What is the best approach for Triangle Judgement?

The direct triangle inequality check is the best approach. Evaluate three conditions: x + y > z, x + z > y, and y + z > x using a SQL CASE expression. It runs in O(n) time because each row is processed once and requires only constant-time comparisons.

Is Triangle Judgement asked at Google/Amazon/Meta?

Triangle Judgement is primarily a SQL practice problem commonly used in database interview preparation. Similar conditional filtering and CASE-based queries appear in interviews at companies like Amazon and Google for roles that require SQL proficiency.

What data structure is used in Triangle Judgement?

No special data structure is required. The problem operates directly on rows in a database table and uses SQL conditional logic such as CASE WHEN with arithmetic comparisons.

What is the time complexity of Triangle Judgement?

The time complexity is O(n), where n is the number of rows in the table. Each row requires a few arithmetic comparisons to verify the triangle inequality. Space complexity is O(1) since no additional data structures are needed.

Comments

Now write it yourselfClose this page and solve Triangle Judgement in the editor, without looking.
Practise Triangle Judgement