Pythagorean Triplet in an array

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C++ program that returns true if there is a Pythagorean
// Triplet in a given aray.
#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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program that returns true if there is a Pythagorean
// Triplet in a given aray.
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 */

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C# program that returns true 
// if there is a Pythagorean
// Triplet in a given aray.
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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A PHP program that returns 
// true if there is a Pythagorean
// Triplet in a given aray.
  
// 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.
?>

chevron_right



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.

  1. Fix ‘a’ as last element of sorted array.
  2. 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.
  3. If no pair found for current ‘a’, then move ‘a’ one position back and repeat step 3.2.

Below is the implementation of above algorithm :

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C++ program that returns true if there is a Pythagorean
// Triplet in a given array.
#include <iostream>
#include <algorithm>
  
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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java program that returns true if there is a Pythagorean
// Triplet in a given aray.
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*/

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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.
?>

chevron_right


Output:

 Yes 

Time complexity of this method is 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



My Personal Notes arrow_drop_up

Improved By : shiv_bhakt, vt_m, vasu_arora



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.