Pythagorean Triplet in an array
Last Updated :
27 Dec, 2023
Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
Example:Â
Input: arr[] = {3, 1, 4, 6, 5}Â
Output: TrueÂ
There is a Pythagorean triplet (3, 4, 5).
Input: arr[] = {10, 4, 6, 12, 5}Â
Output: FalseÂ
There is no Pythagorean triplet.Â
Method 1 (Naive)Â
A simple solution is to run three loops, three loops pick three array elements, and check if the current three elements form a Pythagorean Triplet.Â
Below is the implementation of the above idea :
C++
#include <iostream>
using namespace std;
bool isTriplet( int ar[], int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
for ( int k = j + 1; k < n; k++) {
int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z || z == x + y)
return true ;
}
}
}
return false ;
}
int main()
{
int ar[] = { 3, 1, 4, 6, 5 };
int ar_size = sizeof (ar) / sizeof (ar[0]);
isTriplet(ar, ar_size) ? cout << "Yes" : cout << "No" ;
return 0;
}
|
Java
import java.io.*;
class PythagoreanTriplet {
static boolean isTriplet( int ar[], int n)
{
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
for ( int k = j + 1 ; k < n; k++) {
int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z || z == x + y)
return true ;
}
}
}
return false ;
}
public static void main(String[] args)
{
int ar[] = { 3 , 1 , 4 , 6 , 5 };
int ar_size = ar.length;
if (isTriplet(ar, ar_size) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isTriplet(ar, n):
j = 0
for i in range (n - 2 ):
for j in range (i + 1 , n):
for k in range (j + 1 , n - 1 ):
x = ar[i] * ar[i]
y = ar[j] * ar[j]
z = ar[k] * ar[k]
if (x = = y + z or y = = x + z or z = = x + y):
return 1
return 0
ar = [ 3 , 1 , 4 , 6 , 5 ]
ar_size = len (ar)
if (isTriplet(ar, ar_size)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isTriplet( int [] ar, int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
for ( int k = j + 1; k < n; k++) {
int x = ar[i] * ar[i], y = ar[j] * ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z || z == x + y)
return true ;
}
}
}
return false ;
}
public static void Main()
{
int [] ar = { 3, 1, 4, 6, 5 };
int ar_size = ar.Length;
if (isTriplet(ar, ar_size) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isTriplet( ar, n)
{
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
let x = ar[i] * ar[i], y = ar[j] *
ar[j], z = ar[k] * ar[k];
if (x == y + z || y == x + z ||
z == x + y)
return true ;
}
}
}
return false ;
}
let ar = [ 3, 1, 4, 6, 5 ];
let ar_size = ar.length;
if (isTriplet(ar, ar_size) == true )
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
<?php
function isTriplet( $ar , $n )
{
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = $i + 1; $j < $n ; $j ++)
{
for ( $k = $j + 1; $k < $n ; $k ++)
{
$x = $ar [ $i ] * $ar [ $i ];
$y = $ar [ $j ] * $ar [ $j ];
$z = $ar [ $k ] * $ar [ $k ];
if ( $x == $y + $z or
$y == $x + $z or
$z == $x + $y )
return true;
}
}
}
return false;
}
$ar = array (3, 1, 4, 6, 5);
$ar_size = count ( $ar );
if (isTriplet( $ar , $ar_size ))
echo "Yes" ;
else
echo "No" ;
?>
|
Output:Â
Yes
The Time Complexity of the above solution is O(n3).Â
Auxiliary Space: O(1)
Method 2 (Use Sorting)Â
We can solve this in O(n2) time by sorting the array first.Â
1) Do the square of every element in the input array. This step takes O(n) time.
2) Sort the squared array in increasing order. This step takes O(nLogn) time.
3) To find a triplet (a, b, c) such that a2 = b2 + c2, do following.Â
- Fix ‘a’ as the last element of the sorted array.
- Now search for pair (b, c) in subarray between the first element and ‘a’. A pair (b, c) with a given sum can be found in O(n) time using the meet in middle algorithm discussed in method 1 of this post.
- If no pair is found for current ‘a’, then move ‘a’ one position back and repeat step 3.2.
Below image is a dry run of the above approach:Â
Below is the implementation of the above approach:Â
C++
#include <algorithm>
#include <iostream>
using namespace std;
bool isTriplet( int arr[], int n)
{
for ( int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
sort(arr, arr + n);
for ( int i = n - 1; i >= 2; i--) {
int l = 0;
int r = i - 1;
while (l < r) {
if (arr[l] + arr[r] == arr[i])
return true ;
(arr[l] + arr[r] < arr[i]) ? l++ : r--;
}
}
return false ;
}
int main()
{
int arr[] = { 3, 1, 4, 6, 5 };
int arr_size = sizeof (arr) / sizeof (arr[0]);
isTriplet(arr, arr_size) ? cout << "Yes" : cout << "No" ;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class PythagoreanTriplet {
static boolean isTriplet( int arr[], int n)
{
for ( int i = 0 ; i < n; i++)
arr[i] = arr[i] * arr[i];
Arrays.sort(arr);
for ( int i = n - 1 ; i >= 2 ; i--) {
int l = 0 ;
int r = i - 1 ;
while (l < r) {
if (arr[l] + arr[r] == arr[i])
return true ;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false ;
}
public static void main(String[] args)
{
int arr[] = { 3 , 1 , 4 , 6 , 5 };
int arr_size = arr.length;
if (isTriplet(arr, arr_size) == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def isTriplet(ar, n):
for i in range (n):
ar[i] = ar[i] * ar[i]
ar.sort()
for i in range (n - 1 , 1 , - 1 ):
j = 0
k = i - 1
while (j < k):
if (ar[j] + ar[k] = = ar[i]):
return True
else :
if (ar[j] + ar[k] < ar[i]):
j = j + 1
else :
k = k - 1
return False
ar = [ 3 , 1 , 4 , 6 , 5 ]
ar_size = len (ar)
if (isTriplet(ar, ar_size)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG {
static bool isTriplet( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
Array.Sort(arr);
for ( int i = n - 1; i >= 2; i--) {
int l = 0;
int r = i - 1;
while (l < r) {
if (arr[l] + arr[r] == arr[i])
return true ;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false ;
}
public static void Main()
{
int [] arr = { 3, 1, 4, 6, 5 };
int arr_size = arr.Length;
if (isTriplet(arr, arr_size) == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function isTriplet(arr , n)
{
for (i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
arr.sort((a,b)=>a-b);
for (i = n - 1; i >= 2; i--)
{
var l = 0;
var r = i - 1;
while (l < r)
{
if (arr[l] + arr[r] == arr[i])
return true ;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false ;
}
var arr = [ 3, 1, 4, 6, 5 ];
var arr_size = arr.length;
if (isTriplet(arr, arr_size) == true )
document.write( "Yes" );
else
document.write( "No" );
</script>
|
PHP
<?php
function isTriplet( $arr , $n )
{
for ( $i = 0; $i < $n ; $i ++)
$arr [ $i ] = $arr [ $i ] * $arr [ $i ];
sort( $arr );
for ( $i = $n - 1; $i >= 2; $i --)
{
$l = 0;
$r = $i - 1;
while ( $l < $r )
{
if ( $arr [ $l ] + $arr [ $r ] == $arr [ $i ])
return true;
( $arr [ $l ] + $arr [ $r ] < $arr [ $i ])? $l ++: $r --;
}
}
return false;
}
$arr = array (3, 1, 4, 6, 5);
$arr_size = count ( $arr );
if (isTriplet( $arr , $arr_size ))
echo "Yes" ;
else
echo "No" ;
?>
|
Output:
Yes
The time complexity of this method is O(n2).
Auxiliary Space: O(1)
Method 3: (Using Hashing)Â
The problem can also be solved using hashing. We can use a hash map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet.Â
Below is the implementation of the above approach:Â Â
C++
#include <bits/stdc++.h>
using namespace std;
bool checkTriplet( int arr[], int n)
{
int maximum = 0;
for ( int i = 0; i < n; i++) {
maximum = max(maximum, arr[i]);
}
int hash[maximum + 1] = { 0 };
for ( int i = 0; i < n; i++)
hash[arr[i]]++;
for ( int i = 1; i < maximum + 1; i++) {
if (hash[i] == 0)
continue ;
for ( int j = 1; j < maximum + 1; j++) {
if ((i == j && hash[i] == 1) || hash[j] == 0)
continue ;
int val = sqrt (i * i + j * j);
if ((val * val) != (i * i + j * j))
continue ;
if (val > maximum)
continue ;
if (hash[val]) {
return true ;
}
}
}
return false ;
}
int main()
{
int arr[] = { 3, 2, 4, 6, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
if (checkTriplet(arr, n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
import java.util.*;
class GFG
{
static boolean checkTriplet( int arr[], int n)
{
int maximum = 0 ;
for ( int i = 0 ; i < n; i++)
{
maximum = Math.max(maximum, arr[i]);
}
int []hash = new int [maximum + 1 ];
for ( int i = 0 ; i < n; i++)
hash[arr[i]]++;
for ( int i = 1 ; i < maximum + 1 ; i++)
{
if (hash[i] == 0 )
continue ;
for ( int j = 1 ; j < maximum + 1 ; j++)
{
if ((i == j && hash[i] == 1 ) || hash[j] == 0 )
continue ;
int val = ( int ) Math.sqrt(i * i + j * j);
if ((val * val) != (i * i + j * j))
continue ;
if (val > maximum)
continue ;
if (hash[val] >= 1 )
{
return true ;
}
}
}
return false ;
}
public static void main(String[] args)
{
int arr[] = { 3 , 2 , 4 , 6 , 5 , 5 };
int n = arr.length;
if (checkTriplet(arr, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
import math
def checkTriplet(arr, n):
maximum = 0
maximum = max (arr)
hash = [ 0 ] * (maximum + 1 )
for i in range (n):
hash [arr[i]] + = 1
for i in range ( 1 , maximum + 1 ):
if ( hash [i] = = 0 ):
continue
for j in range ( 1 , maximum + 1 ):
if ((i = = j and hash [i] = = 1 ) or hash [j] = = 0 ):
continue
val = int (math.sqrt(i * i + j * j))
if ((val * val) ! = (i * i + j * j)):
continue
if (val > maximum):
continue
if ( hash [val]):
return True
return False
arr = [ 3 , 2 , 4 , 6 , 5 ]
n = len (arr)
if (checkTriplet(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool checkTriplet( int []arr, int n)
{
int maximum = 0;
for ( int i = 0; i < n; i++)
{
maximum = Math.Max(maximum, arr[i]);
}
int []hash = new int [maximum + 1];
for ( int i = 0; i < n; i++)
hash[arr[i]]++;
for ( int i = 1; i < maximum + 1; i++)
{
if (hash[i] == 0)
continue ;
for ( int j = 1; j < maximum + 1; j++)
{
if ((i == j && hash[i] == 1) || hash[j] == 0)
continue ;
int val = ( int ) Math.Sqrt(i * i + j * j);
if ((val * val) != (i * i + j * j))
continue ;
if (val > maximum)
continue ;
if (hash[val] >= 1)
{
return true ;
}
}
}
return false ;
}
public static void Main(String[] args)
{
int []arr = { 3, 2, 4, 6, 5, 5 };
int n = arr.Length;
if (checkTriplet(arr, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function checkTriplet(arr , n) {
var maximum = 0;
for (i = 0; i < n; i++) {
maximum = Math.max(maximum, arr[i]);
}
var hash = Array(maximum + 1).fill(0);
for (i = 0; i < n; i++)
hash[arr[i]]++;
for (i = 1; i < maximum + 1; i++) {
if (hash[i] == 0)
continue ;
for (j = 1; j < maximum + 1; j++) {
if ((i == j && hash[i] == 1) || hash[j] == 0)
continue ;
var val = parseInt( Math.sqrt(i * i + j * j));
if ((val * val) != (i * i + j * j))
continue ;
if (val > maximum)
continue ;
if (hash[val] == 1) {
return true ;
}
}
}
return false ;
}
var arr = [ 3, 2, 4, 6, 5 ];
var n = arr.length;
if (checkTriplet(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Thanks to Striver for suggesting the above approach.Â
Time Complexity: O( max * max ), where max is the maximum element in the array.Â
Auxiliary Space: O(max)
Method -4:Using STL
Approach:
The problem can be solved using ordered maps and unordered maps. There is no need to store the elements in an ordered manner so implementation by an unordered map is faster. We can use the unordered map to mark all the values of the given array. Using two loops, we can iterate for all the possible combinations of a and b, and then check if there exists the third value c. If there exists any such value, then there is a Pythagorean triplet.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkTriplet( int arr[], int n)
{
unordered_map< int , int > umap;
for ( int i = 0; i < n; i++)
umap[arr[i]] = umap[arr[i]] + 1;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
int p = sqrt (arr[i] * arr[i] + arr[j] * arr[j]);
float q
= sqrt (arr[i] * arr[i] + arr[j] * arr[j]);
if (p == q && umap[p] != 0)
return true ;
}
}
return false ;
}
int main()
{
int arr[] = { 3, 2, 4, 6, 5 };
int n = sizeof (arr) / sizeof (arr[0]);
if (checkTriplet(arr, n))
cout << "Yes" ;
else
cout << "No" ;
}
|
Java
import java.util.*;
class GFG{
static boolean checkTriplet( int arr[], int n)
{
HashMap<Integer,Integer> umap = new HashMap<>();
for ( int i = 0 ; i < n; i++)
if (umap.containsKey(arr[i]))
umap.put(arr[i] , umap.get(arr[i]) + 1 );
else
umap.put(arr[i], 1 );
for ( int i = 0 ; i < n - 1 ; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
int p =( int ) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]);
float q
=( float ) Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]);
if (p == q && umap.get(p) != 0 )
return true ;
}
}
return false ;
}
public static void main(String[] args)
{
int arr[] = { 3 , 2 , 4 , 6 , 5 };
int n = arr.length;
if (checkTriplet(arr, n))
System.out.print( "Yes" );
else
System.out.print( "No" );
}
}
|
Python3
import math
def checkTriplet(arr, n):
h = {arr[i]: 1 for i in range (n)}
for i in range (n - 1 ):
for j in range (i + 1 , n):
q = math.sqrt(arr[i] * arr[i] + arr[j] * arr[j])
if q = = int (q) and int (q) in h:
return True
return False
arr = [ 3 , 2 , 4 , 6 , 5 ]
n = len (arr)
if (checkTriplet(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static bool checkTriplet( int []arr, int n) {
Dictionary< int , int > umap = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
if (umap.ContainsKey(arr[i]))
umap.Add(arr[i], umap[arr[i]] + 1);
else
umap.Add(arr[i], 1);
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
int p = ( int ) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]);
float q = ( float ) Math.Sqrt(arr[i] * arr[i] + arr[j] * arr[j]);
if (p == q && umap[p] != 0)
return true ;
}
}
return false ;
}
public static void Main(String[] args) {
int []arr = { 3, 2, 4, 6, 5 };
int n = arr.Length;
if (checkTriplet(arr, n))
Console.Write( "Yes" );
else
Console.Write( "No" );
}
}
|
Javascript
<script>
function checkTriplet(arr , n) {
var umap = new Map();
for (i = 0; i < n; i++)
if (umap.has(arr[i]))
umap.set(arr[i], umap.get(arr[i]) + 1);
else
umap.set(arr[i], 1);
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
var p = parseInt( Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]));
var q = Math.sqrt(arr[i] * arr[i] + arr[j] * arr[j]);
if (p == q && umap.get(p) != 0)
return true ;
}
}
return false ;
}
var arr = [ 3, 2, 4, 6, 5 ];
var n = arr.length;
if (checkTriplet(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity:O(n2)
Auxiliary Space:O(n)
Â
Method 5 – A better hashing based approach
This approach uses Set. Firstly, we’ll square the elements of the array and then sort the array in increasing order. Run two loops where the outer loop starts from the last index of the array to the second index (0 based indexing is assumed) and the inner loop starts from outerLoopIndex – 1 to the start. Create a set to store the elements in between outerLoopIndex and innerLoopIndex. Check if there is a number in the set which is equal to arr[outerLoopIndex] – arr[innerLoopIndex]. If yes, then return “True”.
C++
#include <bits/stdc++.h>
using namespace std;
bool checkTriplet( int arr[], int n)
{
for ( int i = 0; i < n; i++)
arr[i] = arr[i]*arr[i];
sort(arr, arr + n);
for ( int i = n - 1; i > 1; i--)
{
unordered_set< int > s;
for ( int j = i - 1; j >- 1; j--)
{
if (s.count(arr[i] - arr[j]))
return true ;
s.insert(arr[j]);
}
}
return false ;
}
int main()
{
int arr[] = {3, 2, 4, 6, 5};
int n = sizeof (arr)/ sizeof (arr[0]);
if (checkTriplet(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.Arrays;
import java.util.HashSet;
public class Triplet {
static boolean checkTriplet( int [] arr, int n) {
for ( int i = 0 ; i < n; i++) {
arr[i] = arr[i] * arr[i];
}
Arrays.sort(arr);
for ( int i = n - 1 ; i > 1 ; i--) {
HashSet<Integer> s = new HashSet<>();
for ( int j = i - 1 ; j >= 0 ; j--) {
if (s.contains(arr[i] - arr[j])) {
return true ;
}
s.add(arr[j]);
}
}
return false ;
}
public static void main(String[] args) {
int [] arr = { 3 , 2 , 4 , 6 , 5 };
int n = arr.length;
if (checkTriplet(arr, n)) {
System.out.println( "Yes" );
} else {
System.out.println( "No" );
}
}
}
|
Python3
def checkTriplet(arr, n):
for i in range (n):
arr[i] = arr[i] * arr[i]
arr.sort()
for i in range (n - 1 , 1 , - 1 ):
s = set ()
for j in range (i - 1 , - 1 , - 1 ):
if (arr[i] - arr[j]) in s:
return True
s.add(arr[j])
return False
arr = [ 3 , 2 , 4 , 6 , 5 ]
n = len (arr)
if (checkTriplet(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static bool CheckTriplet( int [] arr, int n)
{
for ( int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
Array.Sort(arr);
for ( int i = n - 1; i > 1; i--)
{
HashSet< int > s = new HashSet< int >();
for ( int j = i - 1; j >= 0; j--)
{
if (s.Contains(arr[i] - arr[j]))
return true ;
s.Add(arr[j]);
}
}
return false ;
}
static void Main()
{
int [] arr = { 3, 2, 4, 6, 5 };
int n = arr.Length;
if (CheckTriplet(arr, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
function checkTriplet(arr, n) {
for (let i = 0; i < n; i++) {
arr[i] = arr[i] * arr[i];
}
arr.sort((a, b) => a - b);
for (let i = n - 1; i >= 2; i--) {
let s = new Set();
for (let j = i - 1; j >= 0; j--) {
if (s.has(arr[i] - arr[j])) {
return true ;
}
s.add(arr[j]);
}
}
return false ;
}
let arr = [3, 2, 4, 6, 5];
let n = arr.length;
if (checkTriplet(arr, n)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(n2)
 Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...