878892. Right Angle Triangle

Easy

Right Angle Triangle

Summary

The problem involves generating all possible right angle triangles with a given set of integer values. The input consists of two integers, and we need to find all possible combinations of two integers from 1 to that can form a right angle triangle.

Detailed Explanation

To solve this problem, we'll use the concept of Pythagorean triples. A right-angled triangle has legs of length a and b, and hypotenuse c. The condition for a right-angled triangle is that a^2 + b^2 = c^2.

We can generate all possible combinations of two integers from 1 to n, calculate their sum as the hypotenuse (c), and check if they satisfy the Pythagorean condition. If they do, we've found another right angle triangle.

Here's the step-by-step solution:

  1. Initialize an empty list to store the right angle triangles.
  2. Iterate through all possible combinations of two integers from 1 to n.
  3. Calculate the sum of the two integers as the hypotenuse (c).
  4. Check if the Pythagorean condition is satisfied: a^2 + b^2 = c^2.
  5. If it is, add the triangle to the list.

Time complexity: O(n^2), where n is the input integer. Space complexity: O(n), as we need to store all possible right angle triangles in the list.

Optimized Solutions

Java

View on GeeksforGeeks
import java.util.ArrayList;
import java.util.List;

public class RightAngleTriangle {
    public static List<String> generateTriangles(int n) {
        List<String> triangles = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            for (int j = i; j <= n; j++) {
                int c = i * i + j * j;
                if (Math.sqrt(c) % 1 == 0) { // Check Pythagorean condition
                    triangles.add(String.format("(%d, %d, %d)", i, j, (int) Math.sqrt(c)));
                }
            }
        }
        return triangles;
    }

    public static void main(String[] args) {
        int n = 5; // Example input
        List<String> triangles = generateTriangles(n);
        System.out.println(triangles);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.