3 Sum Pythagorean Triplet in an array (original) (raw)
Given an array of **positive integers, the task is to determine if a **Pythagorean triplet exists in the given array. A triplet ****{a, b, c}** is considered a Pythagorean triplet if it satisfies the condition **a 2 **+ b 2 = c 2.
**Example:
**Input: arr[] = [3, 1, 4, 6, 5]
**Output: true
**Explanation: The array contains a Pythagorean triplet {3, 4, 5}.**Input: arr[] = [10, 4, 6, 12, 5]
**Output: false
**Explanation: There is no Pythagorean triplet.
Table of Content
- [Naive Approach] Explore all the triplets - O(n^3) Time and O(1) Space
- [Better Approach-1] Two Pointers Technique - O(n^2) Time and O(1) Space
- [Better Approach-2] Using Hashing - O(n^2) Time and O(n) Space
- [Expected Approach] Iterating till max element - O(max(arr)^2) Time and O(max(arr)) Space
[Naive Approach] Explore all the triplets - O(n^3) Time and O(1) Space
The simplest approach is to explore all the triplets(a, b, c) using **three nested loops and if any of them satisfies the condition of Pythagorean Triplet, that is **a 2 + b 2 **= c 2or **a 2 + c 2 **= b2 or **b 2 + c 2 **= a 2 , return true.
C++ `
// C++ program to find if a Pythagorean triplet exists // by exploring all triplets
#include #include using namespace std;
bool pythagoreanTriplet(vector &arr) { int n = arr.size();
// Exploring all possible triplets
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 = arr[i] * arr[i];
int y = arr[j] * arr[j];
int z = arr[k] * arr[k];
// If these integers form Pythagorean triplet then
// return true
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
return false;}
int main() { vector arr = {3, 1, 4, 6, 5}; cout << (pythagoreanTriplet(arr) ? "true" : "false"); return 0; }
C
// C program to find if a Pythagorean triplet exists // by exploring all triplets
#include <stdio.h> #include <stdbool.h>
bool pythagoreanTriplet(int arr[], int n) {
// Exploring all possible triplets
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 = arr[i] * arr[i];
int y = arr[j] * arr[j];
int z = arr[k] * arr[k];
// If these integers form Pythagorean triplet then
// return true
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
return false;}
int main() { int arr[] = {3, 1, 4, 6, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf(pythagoreanTriplet(arr, n) ? "true" : "false");
return 0;}
Java
// Java program to find if a Pythagorean triplet exists // by exploring all triplets
import java.util.*;
class GfG { static boolean pythagoreanTriplet(int[] arr) { int n = arr.length;
// Exploring all possible triplets
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 = arr[i] * arr[i];
int y = arr[j] * arr[j];
int z = arr[k] * arr[k];
// If these integers form Pythagorean triplet then
// return true
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 6, 5};
System.out.println(pythagoreanTriplet(arr));
}}
Python
Python program to find if a Pythagorean triplet exists
by exploring all triplets
def pythagoreanTriplet(arr): n = len(arr)
# Exploring all possible triplets
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
# Calculate square of array elements
x = arr[i] ** 2
y = arr[j] ** 2
z = arr[k] ** 2
# If these integers form Pythagorean triplet then
# return true
if x == y + z or y == x + z or z == x + y:
return True
return Falseif name == "main":
arr = [3, 1, 4, 6, 5]
if pythagoreanTriplet(arr):
print("true")
else :
print("false")
C#
// C# program to find if a Pythagorean triplet exists // by exploring all triplets
using System;
class GfG { static bool pythagoreanTriplet(int[] arr) { int n = arr.Length;
// Exploring all possible triplets
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 = arr[i] * arr[i];
int y = arr[j] * arr[j];
int z = arr[k] * arr[k];
// If these integers form Pythagorean triplet then
// return true
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
return false;
}
static void Main() {
int[] arr = {3, 1, 4, 6, 5};
Console.WriteLine(pythagoreanTriplet(arr)?"true":"false");
}}
JavaScript
// JavaScript program to find if a Pythagorean triplet exists // by exploring all triplets
function pythagoreanTriplet(arr) { let n = arr.length;
// Exploring all possible triplets
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
for (let k = j + 1; k < n; k++) {
// Calculate square of array elements
let x = arr[i] * arr[i];
let y = arr[j] * arr[j];
let z = arr[k] * arr[k];
// If these integers form Pythagorean triplet then
// return true
if (x == y + z || y == x + z || z == x + y)
return true;
}
}
}
return false;}
let arr = [3, 1, 4, 6, 5]; console.log(pythagoreanTriplet(arr));
`
[Better Approach-1] Two Pointers Technique - O(n^2) Time and O(1) Space
The idea is to **square each element of the array and sort it in ascending order. Then, we will traverse the array in reverse and fix the largest element of the triplet as **c 2. After that, we will use two-pointers technique to find two elements **a 2and **b 2 in remaining array such that **a 2 **+ b 2 **= c 2. We initialize two pointers at both ends of the remaining portion of the array (from index 0 to i−1) and adjust them based on the sum of the elements at both pointers as follows:
- If **sum = **c 2, we have found the Pythagorean triplet.
- If **sum < **c 2, we move the **left pointer towards right.
- If **sum > **c 2, we move the **right pointer towards left. C++ `
// C++ program to find if a Pythagorean triplet
// exists using the two-pointer technique
#include #include #include using namespace std;
bool pythagoreanTriplet(vector &arr) { int n = arr.size();
// Taking Square of each element
for (int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
sort(arr.begin(), arr.end());
// fix the largest element of Pythagorean triplet
for (int i = n - 1; i > 1; i--) {
// Two pointer technique to find remaining two
// elements such that a^2 + b^2 = c^2
int l = 0;
int r = i - 1;
while (l < r) {
// A Pythagorean triplet is found
if (arr[l] + arr[r] == arr[i])
return true;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false;}
int main() { vector arr = {3, 1, 4, 6, 5}; cout << (pythagoreanTriplet(arr) ? "true" : "false");
return 0;}
C
// C program to find if a Pythagorean triplet
// exists using the two-pointer technique
#include <stdio.h> #include <stdlib.h> #include <stdbool.h>
int compare(const void *a, const void b) { return ((int *)a - *(int *)b); }
bool pythagoreanTriplet(int arr[], int n) {
// Taking Square of each element
for (int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
// Sort the array
qsort(arr, n, sizeof(int), compare);
// Fix the largest element of Pythagorean triplet
for (int i = n - 1; i > 1; i--) {
// Two pointer technique to find remaining two
// elements such that a^2 + b^2 = c^2
int l = 0;
int r = i - 1;
while (l < r) {
// A Pythagorean triplet is found
if (arr[l] + arr[r] == arr[i])
return true;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false;}
int main() { int arr[] = {3, 1, 4, 6, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf(pythagoreanTriplet(arr, n) ? "true" : "false");
return 0;}
Java
// Java program to find if a Pythagorean triplet
// exists using the two-pointer technique
import java.util.Arrays;
class GfG { static boolean pythagoreanTriplet(int[] arr) { int n = arr.length;
// Taking Square of each element
for (int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
Arrays.sort(arr);
// Fix the largest element of Pythagorean triplet
for (int i = n - 1; i > 1; i--) {
// Two pointer technique to find remaining two
// elements Such that a^2 + b^2 = c^2
int l = 0;
int r = i - 1;
while (l < r) {
// A Pythagorean triplet is found
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};
System.out.println(pythagoreanTriplet(arr));
}}
Python
Python program to find if a Pythagorean triplet
exists using the two-pointer technique
def pythagoreanTriplet(arr): n = len(arr)
# Taking Square of each element
for i in range(n):
arr[i] = arr[i] * arr[i]
arr.sort()
# Fix the largest element of Pythagorean triplet
for i in range(n - 1, 1, -1):
# Two pointer technique to find remaining two
# elements such that a^2 + b^2 = c^2
l = 0
r = i - 1
while l < r:
# A Pythagorean triplet is found
if arr[l] + arr[r] == arr[i]:
return True
if arr[l] + arr[r] < arr[i]:
l += 1
else:
r -= 1
return Falseif name == "main": arr = [3, 1, 4, 6, 5] print("true" if pythagoreanTriplet(arr) else "false")
C#
// C# program to find if a Pythagorean triplet
// exists using the two-pointer technique
using System;
class GfG { static bool pythagoreanTriplet(int[] arr) { int n = arr.Length;
// Taking Square of each element
for (int i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
Array.Sort(arr);
// Fix the largest element of Pythagorean triplet
for (int i = n - 1; i > 1; i--) {
// Two pointer technique to find remaining two elements
// such that a^2 + b^2 = c^2
int l = 0;
int r = i - 1;
while (l < r) {
// A Pythagorean triplet is found
if (arr[l] + arr[r] == arr[i])
return true;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false;
}
static void Main() {
int[] arr = {3, 1, 4, 6, 5};
Console.WriteLine(pythagoreanTriplet(arr)?"true":"false");
}}
JavaScript
// JavaScript program to find if a Pythagorean triplet
// exists using the two-pointer technique
function pythagoreanTriplet(arr) { let n = arr.length;
// Taking Square of each element
for (let i = 0; i < n; i++)
arr[i] = arr[i] * arr[i];
arr.sort((a, b) => a - b);
// Fix the largest element of Pythagorean triplet
for (let i = n - 1; i > 1; i--) {
// Two pointer technique to find remaining two
// elements such that a^2 + b^2 = c^2
let l = 0;
let r = i - 1;
while (l < r) {
// A Pythagorean triplet is found
if (arr[l] + arr[r] === arr[i])
return true;
if (arr[l] + arr[r] < arr[i])
l++;
else
r--;
}
}
return false;}
// Driver Code const arr = [3, 1, 4, 6, 5]; console.log(pythagoreanTriplet(arr));
`
[Better Approach-2] Using Hashing - O(n^2) Time and O(n) Space
First, we will insert all the elements of the given array into a **hash set. Then, using two nested loops, we will iterate through all possible combinations of **a and **b, and check if there exists a third value **c that forms a Pythagorean triplet with **a and **b. If such c exists, we will return true.
C++ `
// C++ program to find if a Pythagorean triplet exists // using hashing
#include #include #include #include <math.h>
using namespace std;
bool pythagoreanTriplet(vector &arr) { int n = arr.size(); unordered_set st; for (int i = 0; i < n; i++) st.insert(arr[i]);
// Iterate through all possible values of a and b
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int a = arr[i];
int b = arr[j];
// calculate required value for
// c to form Pythagorean triplet
int c = sqrt(a * a + b * b);
// First, verify if c^2 is a perfect square (indicating a
// valid c) and check if this c exists in the set.
if (c*c == a*a + b*b && st.find(c) != st.end())
return true;
}
}
// No Pythagorean triplet exists in the array
return false;}
int main() { vector arr = {3, 1, 4, 6, 5}; cout << (pythagoreanTriplet(arr) ? "true" : "false");
return 0;}
Java
// Java program to find if a Pythagorean triplet exists // using hashing
import java.util.HashSet;
class GfG { static boolean pythagoreanTriplet(int[] arr) { int n = arr.length; HashSet st = new HashSet<>(); for (int i = 0; i < n; i++) st.add(arr[i]);
// Iterate through all possible values of a and b
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int a = arr[i];
int b = arr[j];
// calculate required value for
// c to form Pythagorean triplet
int c = (int)Math.sqrt(a * a + b * b);
// First, verify if c^2 is a perfect square (indicating a
// valid c) and check if this c exists in the set.
if (c*c == a*a + b*b && st.contains(c))
return true;
}
}
// No Pythagorean triplet exists in the array
return false;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 6, 5};
System.out.println(pythagoreanTriplet(arr));
}}
Python
Python program to find if a Pythagorean triplet exists
using hashing
def pythagoreanTriplet(arr): n = len(arr) st = set()
for i in range(n):
st.add(arr[i])
# Iterate through all possible values of a and b
for i in range(n - 1):
for j in range(i + 1, n):
a = arr[i]
b = arr[j]
# calculate required value for
# c to form Pythagorean triplet
c = (int)((a ** 2 + b ** 2) ** 0.5)
# First, verify if c^2 is a perfect square (indicating a
# valid c) and check if this c exists in the set.
if (c*c == a*a + b*b) and (c in st):
return True
# No Pythagorean triplet exists in the array
return Falseif name == "main": arr = [3, 1, 4, 6, 5] print("true" if pythagoreanTriplet(arr) else "false")
C#
// C# program to find if a Pythagorean triplet exists // using hashing
using System; using System.Collections.Generic;
class GfG { static bool pythagoreanTriplet(int[] arr) { HashSet st = new HashSet(); int n = arr.Length; for (int i = 0; i < n; i++) st.Add(arr[i]);
// Iterate through all possible values of a and b
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int a = arr[i];
int b = arr[j];
// calculate required value for
// c to form Pythagorean triplet
int c = (int)Math.Sqrt(a * a + b * b);
// First, verify if c^2 is a perfect square (indicating a
// valid c) and check if this c exists in the set.
if (c*c == a*a + b*b && st.Contains(c))
return true;
}
}
// No Pythagorean triplet exists in the array
return false;
}
static void Main() {
int[] arr = {3, 1, 4, 6, 5};
Console.WriteLine(pythagoreanTriplet(arr)?"true":"false");
}}
JavaScript
// JavaScript program to find if a Pythagorean triplet exists // using hashing
function pythagoreanTriplet(arr) { const st = new Set(); const n = arr.length; for (let i = 0; i < n; i++) st.add(arr[i]);
// Iterate through all possible values of a and b
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
const a = arr[i]
const b = arr[j]
// calculate required value for
// c to form Pythagorean triplet
const c = Math.sqrt(a * a + b * b);
// First, verify if c^2 is a perfect square (indicating a
// valid c) and check if this c exists in the set.
if (c*c === a*a + b*b && st.has(c))
return true;
}
}
// No Pythagorean triplet exists in the array
return false;}
const arr = [3, 1, 4, 6, 5]; console.log(pythagoreanTriplet(arr) ? "true" : "false");
`
[Expected Approach] Iterating till max element - O(max(arr)^2) Time and O(max(arr)) Space
The idea is to generate all possible pairs ****(a, b)** within the range of **maximum element in the input array using nested loops. For each pair, calculate the value of **c required to form a **Pythagorean Triplet and check if **c exists in the input array. We can check if c exists or not in **constant time by marking all the elements of input array in a **visited array.
Here, we only need to mark the elements and not store their frequency because for all **valid triplets of **positive integers ****(a, b, c),** no two elements can be equal, that is **a != b, **a != c and **b != c.
**Note: This approach is more efficient than the previous ones, given the constraint (max(arr) < n).
C++ `
// C++ program to find if a Pythagorean triplet
// exists by iterating till max element
#include #include #include using namespace std;
bool pythagoreanTriplet(vector &arr) { int n = arr.size(); int maxEle = 0; for (int ele: arr) maxEle = max(maxEle, ele);
// Visited array to mark the elements
vector<bool> vis(maxEle + 1, 0);
// Marking each element of input array
for (int ele: arr)
vis[ele] = true;
// Iterate for all possible a
for (int a = 1; a < maxEle + 1; a++) {
// If a is not there
if (vis[a] == false)
continue;
// Iterate for all possible b
for (int b = 1; b < maxEle + 1; b++) {
// If b is not there
if (vis[b] == false)
continue;
// calculate c value to form a pythagorean triplet
int c = sqrt(a * a + b * b);
// If c^2 is not a perfect square or c exceeds the
// maximum value
if ((c * c) != (a * a + b * b) || c > maxEle)
continue;
// If there exists c in the original array,
// we have found the triplet
if (vis[c] == true) {
return true;
}
}
}
return false;}
int main() { vector arr = {3, 1, 4, 6, 5}; cout << (pythagoreanTriplet(arr) ? "true" : "false");
return 0;}
Java
// Java program to find if a Pythagorean triplet
// exists by iterating till max element
import java.util.Arrays;
class GfG { static boolean pythagoreanTriplet(int[] arr) { int n = arr.length; int maxEle = 0; for (int ele : arr) maxEle = Math.max(maxEle, ele);
// Visited array to mark the elements
boolean[] vis = new boolean[maxEle + 1];
// Marking each element of input array
for (int ele : arr)
vis[ele] = true;
// Iterate for all possible a
for (int a = 1; a < maxEle + 1; a++) {
// If a is not there
if (!vis[a])
continue;
// Iterate for all possible b
for (int b = 1; b < maxEle + 1; b++) {
// If b is not there
if (!vis[b])
continue;
// calculate c value to form a pythagorean triplet
int c = (int) Math.sqrt(a * a + b * b);
// If c^2 is not a perfect square or c exceeds the
// maximum value
if ((c * c) != (a * a + b * b) || c > maxEle)
continue;
// If there exists c in the original array,
// we have found the triplet
if (vis[c]) {
return true;
}
}
}
return false;
}
public static void main(String[] args) {
int[] arr = {3, 1, 4, 6, 5};
System.out.println(pythagoreanTriplet(arr));
}}
Python
Python program to find if a Pythagorean triplet
exists by iterating till max element
import math
def pythagoreanTriplet(arr): n = len(arr) maxEle = 0 for ele in arr: maxEle = max(maxEle, ele)
# Visited array to mark the elements
vis = [False] * (maxEle + 1)
# Marking each element of input array
for ele in arr:
vis[ele] = True
# Iterate for all possible a
for a in range(1, maxEle + 1):
# If a is not there
if not vis[a]:
continue
# Iterate for all possible b
for b in range(1, maxEle + 1):
# If b is not there
if not vis[b]:
continue
# calculate c value to form a pythagorean triplet
c = int(math.sqrt(a * a + b * b))
# If c^2 is not a perfect square or c exceeds the
# maximum value
if (c * c) != (a * a + b * b) or c > maxEle:
continue
# If there exists c in the original array,
# we have found the triplet
if vis[c]:
return True
return Falseif name == "main": arr = [3, 1, 4, 6, 5] ans = pythagoreanTriplet(arr)
if ans:
print("true")
else :
print("false")C#
// C# program to find if a Pythagorean triplet
// exists by iterating till max element
using System; using System.Collections.Generic;
class GfG { static bool pythagoreanTriplet(int[] arr) { int n = arr.Length; int maxEle = 0; foreach (int ele in arr) maxEle = Math.Max(maxEle, ele);
// Visited array to mark the elements
bool[] vis = new bool[maxEle + 1];
// Marking each element of input array
foreach (int ele in arr)
vis[ele] = true;
// Iterate for all possible a
for (int a = 1; a < maxEle + 1; a++) {
// If a is not there
if (vis[a] == false)
continue;
// Iterate for all possible b
for (int b = 1; b < maxEle + 1; b++) {
// If b is not there
if (vis[b] == false)
continue;
// calculate c value to form a pythagorean triplet
int c = (int)Math.Sqrt(a * a + b * b);
// If c^2 is not a perfect square or c exceeds the
// maximum value
if ((c * c) != (a * a + b * b) || c > maxEle)
continue;
// If there exists c in the original array,
// we have found the triplet
if (vis[c] == true)
return true;
}
}
return false;
}
static void Main() {
int[] arr = { 3, 1, 4, 6, 5 };
bool ans = pythagoreanTriplet(arr);
if (ans)
Console.WriteLine("true");
else
Console.WriteLine("false");
}}
JavaScript
// JavaScript program to find if a Pythagorean triplet
// exists by iterating till max element
function pythagoreanTriplet(arr) { let n = arr.length; let maxEle = 0; for (let ele of arr) maxEle = Math.max(maxEle, ele);
// Visited array to mark the elements
let vis = new Array(maxEle + 1).fill(false);
// Marking each element of input array
for (let ele of arr)
vis[ele] = true;
// Iterate for all possible a
for (let a = 1; a < maxEle + 1; a++) {
// If a is not there
if (vis[a] === false)
continue;
// Iterate for all possible b
for (let b = 1; b < maxEle + 1; b++) {
// If b is not there
if (vis[b] === false)
continue;
// calculate c value to form a pythagorean triplet
let c = Math.floor(Math.sqrt(a * a + b * b));
// If c^2 is not a perfect square or c exceeds the
// maximum value
if ((c * c) !== (a * a + b * b) || c > maxEle)
continue;
// If there exists c in the original array,
// we have found the triplet
if (vis[c] === true) {
return true;
}
}
}
return false;}
const arr = [3, 1, 4, 6, 5]; console.log(pythagoreanTriplet(arr));
`