How to find Pythagorean triplets in an array
A Pythagorean triplet is a set {a, b, c} such that . The user is provided with an array of integers and has to identify all the possible sets of Pythagorean triplets.
Algorithm
The naive approach here would be to run three nested for loops to try all possible triplets in an array. However, the complexity of such a solution would be .
Instead, we can solve the problem in by sorting the array in ascending order, first.
The steps involved would be:
- Square every element in the input array and then sort it in ascending order.
- Since the array now contains squares, the new equation for triplet becomes . Fix
ato be the last element of this sorted array, sinceawill always have the largest value of the three numbers. - Fix
bas the first element of the sorted array andcas the element right before elementa. Since numbers are positive and the array is sorted, and . To find triplets, run a loop that increasesbfrom to , and decreasescfrom to at the same time until they meet.- Increase the position of
bif . - Decrease the position of
cif . - If the sum is equal to
a, then print the square root of the three numbers, incrementb, and decrementc. - Repeat the last step for each element
ain the array.
- Increase the position of
The following slides help us to visualize this algorithm:​
1 of 11
Code
#include <algorithm>#include <iostream>#include <math.h>using namespace std;void findTriplet(int arr[], int n){// Step 1for (int i = 0; i < n; i++)arr[i] = arr[i] * arr[i];// Sort array elementssort(arr, arr + n);// Step 2 and Step 3for (int i = n - 1; i >= 2; i--) { // Fixing aint b = 0; // Fixing bint c = i - 1; // Fixing cwhile (b < c) {// A triplet foundif (arr[b] + arr[c] == arr[i]){cout << "Triplet: "<< sqrt(arr[b]) <<", "<< sqrt(arr[c]) <<", "<< sqrt(arr[i])<<"\n";b++;c--;}// Else either move 'b' or 'c'else if (arr[b] + arr[c] < arr[i]) {b++;}else {c--;}}}}// Driver codeint main(){int arr[] = { 3, 1, 4, 6, 5 };int n = sizeof(arr) / sizeof(arr[0]);findTriplet(arr, n);return 0;}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved