VOOZH about

URL: https://www.geeksforgeeks.org/dsa/pythagorean-triplet-given-sum/

⇱ Find Pythagorean Triplet with given sum - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Pythagorean Triplet with given sum

Last Updated : 11 Jul, 2025

Given a positive integer target, the task is to find all Pythagorean Triplets whose sum of the elements is equal to the given target. A triplet {a, b, c} is considered a Pythagorean triplet if it satisfies the condition a2 + b2 = c2.

Examples :

Input: target = 60
Output: {{10, 24, 26}, {15, 20, 25}}
Explanation: There are two Pythagorean triplets: {10, 24, 26} and {15, 20, 25}, both having a sum equal to 60.

Input : target = 4
Output : {}
Explanation: No Pythagorean triplet exists with a sum of 4.

[Naive Approach] - Using three nested loops - O(n^3) Time and O(1) Space

A simple solution is to generate all possible triplets using three nested loops and for every triplet, check if it is a Pythagorean Triplet and the sum of its elements is equal to given target.


Output
10 24 26
15 20 25

[Better Approach] - Using two nested loops - O(n^2) Time and O(1) Space

This approach is an optimization to the previous one. In this, we run two nested loops to generate all possible values of first two elements of the triplet. The third element can be found by subtracting these values from the given target. We then check whether these elements form a Pythagorean triplet.


Output
10 24 26
15 20 25

[Expected Approach] - Using Mathematical Formula - O(n) Time and O(1) Space

We know that the sum of all the elements in a valid triplet is equal to the given target, i.e., a + b + c = target, and it is a Pythagorean Triplet, i.e., a2 + b2 = c2. Now, we can derive the value of c in terms of variable a using these two equations. Then, for all possible values of a, we calculate the corresponding valid c values. Finally, values of b can be found by subtracting a and c from the target.

You can refer to this article for complete implementation of this approach - Find Pythagorean Triplet with given sum using Mathematical Formula.


Comment
Article Tags: