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 current three elements form a Pythagorean Triplet.
Below is the implementation of above idea :
C++
// A C++ program that returns true if there is a Pythagorean // Triplet in a given array. #include <iostream> using namespace std; // Returns true if there is Pythagorean triplet in ar[0..n-1] 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++) { // Calculate square of array elements 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 ; } } } // If we reach here, no triplet found return false ; } /* Driver program to test above function */ 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
// A Java program that returns true if there is a Pythagorean // Triplet in a given array. import java.io.*; class PythagoreanTriplet { // Returns true if there is Pythagorean triplet in ar[0..n-1] 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++) { // Calculate square of array elements 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 ; } } } // If we reach here, no triplet found return false ; } // Driver program to test above function 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" ); } } /* This code is contributed by Devesh Agrawal */ |
Python3
# Python program to check if there is Pythagorean # triplet in given array # Returns true if there is Pythagorean # triplet in ar[0..n-1] def isTriplet(ar, n): j = 0 for i in range (n - 2 ): for k in range (j + 1 , n): for j in range (i + 1 , n - 1 ): # Calculate square of array elements 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 # If we reach here, no triplet found return 0 # Driver program to test above function ar = [ 3 , 1 , 4 , 6 , 5 ] ar_size = len (ar) if (isTriplet(ar, ar_size)): print ( "Yes" ) else : print ( "No" ) # This code is contributed by Aditi Sharma |
C#
// A C# program that returns true // if there is a Pythagorean // Triplet in a given array. using System; class GFG { // Returns true if there is Pythagorean // triplet in ar[0..n-1] 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++) { // Calculate square of array elements 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 ; } } } // If we reach here, // no triplet found return false ; } // Driver code 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" ); } } // This code is contributed by shiv_bhakt. |
PHP
<?php // A PHP program that returns // true if there is a Pythagorean // Triplet in a given array. // Returns true if there is // Pythagorean triplet in // ar[0..n-1] function isTriplet( $ar , $n ) { for ( $i = 0; $i < $n ; $i ++) { for ( $j = $i + 1; $j < $n ; $j ++) { for ( $k = $j + 1; $k < $n ; $k ++) { // Calculate square of // array elements $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; } } } // If we reach here, // no triplet found return false; } // Driver Code $ar = array (3, 1, 4, 6, 5); $ar_size = count ( $ar ); if (isTriplet( $ar , $ar_size )) echo "Yes" ; else echo "No" ; // This code is contributed by anuj_67. ?> |
Output:
Yes
Time Complexity of the above solution is O(n3).
Method 2 (Use Sorting)
We can solve this in O(n2) time by sorting the array first.
1) Do square of every element in 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 last element of sorted array.
- Now search for pair (b, c) in subarray between first element and ‘a’. A pair (b, c) with given sum can be found in O(n) time using meet in middle algorithm discussed in method 1 of this post.
- If no pair 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++
// A C++ program that returns true if there is a Pythagorean // Triplet in a given array. #include <algorithm> #include <iostream> using namespace std; // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array bool isTriplet( int arr[], int n) { // Square array elements for ( int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements sort(arr, arr + n); // Now fix one element one by one and find the other two // elements for ( int i = n - 1; i >= 2; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0; // index of the first element in arr[0..i-1] int r = i - 1; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true ; // Else either move 'l' or 'r' (arr[l] + arr[r] < arr[i]) ? l++ : r--; } } // If we reach here, then no triplet found return false ; } /* Driver program to test above function */ 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
// A Java program that returns true if there is a Pythagorean // Triplet in a given array. import java.io.*; import java.util.*; class PythagoreanTriplet { // Returns true if there is a triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies given array static boolean isTriplet( int arr[], int n) { // Square array elements for ( int i = 0 ; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Arrays.sort(arr); // Now fix one element one by one and find the other two // elements for ( int i = n - 1 ; i >= 2 ; i--) { // To find the other two elements, start two index // variables from two corners of the array and move // them toward each other int l = 0 ; // index of the first element in arr[0..i-1] int r = i - 1 ; // index of the last element in arr[0..i-1] while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true ; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then no triplet found return false ; } // Driver program to test above function 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" ); } } /*This code is contributed by Devesh Agrawal*/ |
Python3
# Python program that returns true if there is # a Pythagorean Triplet in a given array. # Returns true if there is Pythagorean # triplet in ar[0..n-1] def isTriplet(ar, n): # Square all the elemennts for i in range (n): ar[i] = ar[i] * ar[i] # sort array elements ar.sort() # fix one element # and find other two # i goes from n - 1 to 2 for i in range (n - 1 , 1 , - 1 ): # start two index variables from # two corners of the array and # move them toward each other j = 0 k = i - 1 while (j < k): # A triplet found if (ar[j] + ar[k] = = ar[i]): return True else : if (ar[j] + ar[k] < ar[i]): j = j + 1 else : k = k - 1 # If we reach here, then no triplet found return False # Driver program to test above function */ ar = [ 3 , 1 , 4 , 6 , 5 ] ar_size = len (ar) if (isTriplet(ar, ar_size)): print ( "Yes" ) else : print ( "No" ) # This code is contributed by Aditi Sharma |
C#
// C# program that returns true // if there is a Pythagorean // Triplet in a given array. using System; class GFG { // Returns true if there is a triplet // with following property A[i]*A[i] // = A[j]*A[j]+ A[k]*[k] Note that // this function modifies given array static bool isTriplet( int [] arr, int n) { // Square array elements for ( int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort array elements Array.Sort(arr); // Now fix one element one by one // and find the other two elements for ( int i = n - 1; i >= 2; i--) { // To find the other two elements, // start two index variables from // two corners of the array and // move them toward each other // index of the first element // in arr[0..i-1] int l = 0; // index of the last element // in arr[0..i - 1] int r = i - 1; while (l < r) { // A triplet found if (arr[l] + arr[r] == arr[i]) return true ; // Else either move 'l' or 'r' if (arr[l] + arr[r] < arr[i]) l++; else r--; } } // If we reach here, then // no triplet found return false ; } // Driver Code 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" ); } } // This code is contributed by shiv_bhakt. |
PHP
<?php // A PHP program that returns // true if there is a Pythagorean // Triplet in a given array. // Returns true if there is a // triplet with following property // A[i]*A[i] = A[j]*A[j] + A[k]*[k] // Note that this function modifies // given array function isTriplet( $arr , $n ) { // Square array elements for ( $i = 0; $i < $n ; $i ++) $arr [ $i ] = $arr [ $i ] * $arr [ $i ]; // Sort array elements sort( $arr ); // Now fix one element one by // one and find the other two // elements for ( $i = $n - 1; $i >= 2; $i --) { // To find the other two // elements, start two index // variables from two corners // of the array and move // them toward each other // index of the first element // in arr[0..i-1] $l = 0; // index of the last element // in arr[0..i-1] $r = $i - 1; while ( $l < $r ) { // A triplet found if ( $arr [ $l ] + $arr [ $r ] == $arr [ $i ]) return true; // Else either move 'l' or 'r' ( $arr [ $l ] + $arr [ $r ] < $arr [ $i ])? $l ++: $r --; } } // If we reach here, // then no triplet found return false; } // Driver Code $arr = array (3, 1, 4, 6, 5); $arr_size = count ( $arr ); if (isTriplet( $arr , $arr_size )) echo "Yes" ; else echo "No" ; // This code is contributed by anuj_67. ?> |
Output:
Yes
Time complexity of this method is O(n2).
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; // Function to check if the // Pythagorean triplet exists or not bool checkTriplet( int arr[], int n) { int maximum = 0; // Find the maximum element for ( int i = 0; i < n; i++) { maximum = max(maximum, arr[i]); } // Hashing array int hash[maximum + 1] = { 0 }; // Increase the count of array elements // in hash table for ( int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for ( int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue ; // Iterate for all possible b for ( int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue ; // Find c int val = sqrt (i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue ; // If c exceeds the maximum value if (val > maximum) continue ; // If there exists c in the original array, // we have the triplet if (hash[val]) { return true ; } } } return false ; } // Driver Code 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 { // Function to check if the // Pythagorean triplet exists or not static boolean checkTriplet( int arr[], int n) { int maximum = 0 ; // Find the maximum element for ( int i = 0 ; i < n; i++) { maximum = Math.max(maximum, arr[i]); } // Hashing array int []hash = new int [maximum + 1 ]; // Increase the count of array elements // in hash table for ( int i = 0 ; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for ( int i = 1 ; i < maximum + 1 ; i++) { // If a is not there if (hash[i] == 0 ) continue ; // Iterate for all possible b for ( int j = 1 ; j < maximum + 1 ; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1 ) || hash[j] == 0 ) continue ; // Find c int val = ( int ) Math.sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue ; // If c exceeds the maximum value if (val > maximum) continue ; // If there exists c in the original array, // we have the triplet if (hash[val] == 1 ) { return true ; } } } return false ; } // Driver Code 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" ); } } // This code is contributed by Rajput-Ji |
Python3
# Function to check if the # Pythagorean triplet exists or not import math def checkTriplet(arr, n): maximum = 0 # Find the maximum element for i in range (n): maximum = max (maximum, arr[i]) # Hashing array hash = [ 0 ] * (maximum + 1 ) # Increase the count of array elements # in hash table for i in range (n): hash [arr[i]] + = 1 # Iterate for all possible a for i in range ( 1 , maximum + 1 ): # If a is not there if ( hash [i] = = 0 ): continue # Iterate for all possible b for j in range ( 1 , maximum + 1 ): # If a and b are same and there is only one a # or if there is no b in original array if ((i = = j and hash [i] = = 1 ) or hash [j] = = 0 ): continue # Find c val = int (math.sqrt(i * i + j * j)) # If c^2 is not a perfect square if ((val * val) ! = (i * i + j * j)): continue # If c exceeds the maximum value if (val > maximum): continue # If there exists c in the original array, # we have the triplet if ( hash [val]): return True return False # Driver Code arr = [ 3 , 2 , 4 , 6 , 5 ] n = len (arr) if (checkTriplet(arr, n)): print ( "Yes" ) else : print ( "No" ) # This code is contributed by ankush_953 |
C#
using System; class GFG { // Function to check if the // Pythagorean triplet exists or not static bool checkTriplet( int []arr, int n) { int maximum = 0; // Find the maximum element for ( int i = 0; i < n; i++) { maximum = Math.Max(maximum, arr[i]); } // Hashing array int []hash = new int [maximum + 1]; // Increase the count of array elements // in hash table for ( int i = 0; i < n; i++) hash[arr[i]]++; // Iterate for all possible a for ( int i = 1; i < maximum + 1; i++) { // If a is not there if (hash[i] == 0) continue ; // Iterate for all possible b for ( int j = 1; j < maximum + 1; j++) { // If a and b are same and there is only one a // or if there is no b in original array if ((i == j && hash[i] == 1) || hash[j] == 0) continue ; // Find c int val = ( int ) Math.Sqrt(i * i + j * j); // If c^2 is not a perfect square if ((val * val) != (i * i + j * j)) continue ; // If c exceeds the maximum value if (val > maximum) continue ; // If there exists c in the original array, // we have the triplet if (hash[val] == 1) { return true ; } } } return false ; } // Driver Code 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" ); } } // This code is contributed by Rajput-Ji |
Output:
Yes
Thanks to Striver for suggesting the above approach.
Time Complexity: O( max * max ), where max is the maximum most element in the array.
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 ordered manner so implementation by unordered map is faster. We can use 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; // Returns true if there is Pythagorean triplet in // ar[0..n-1] bool checkTriplet( int arr[], int n) { // initializing unordered map with key and value as // integers unordered_map< int , int > umap; // Increase the count of array elements in unordered map 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++) { // calculating the squares of two elements as // integer and float int p = sqrt (arr[i] * arr[i] + arr[j] * arr[j]); float q = sqrt (arr[i] * arr[i] + arr[j] * arr[j]); // Condition is true if the value is same in // integer and float and also the value is // present in unordered map if (p == q && umap[p] != 0) return true ; } } // If we reach here, no triplet found return false ; } // Driver Code 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" ; } // This code is contributed by Vikkycirus |
Yes
Time Complexity:O(n2)
This article is contributed by Harshit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.