25. Pythagorean Triplet
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given an integer array arr[]
, determine if there exists a triplet (a, b, c)
in the array such that they satisfy the Pythagorean condition:
where a
, b
, and c
are elements at different indices of the array.
๐ Examples
Example 1:
Input:
arr = [3, 2, 4, 6, 5]
Output:
true
Explanation:
The triplet (3, 4, 5)
satisfies $3^2 + 4^2 = 5^2$.
Example 2:
Input:
arr = [3, 8, 5]
Output:
false
Explanation:
No triplet satisfies the Pythagorean condition.
Example 3:
Input:
arr = [1, 1, 1]
Output:
false
Explanation:
No such triplet possible.
๐ Constraints
$1 \leq \text{arr.size()} \leq 10^5$
$1 \leq \text{arr}[i] \leq 10^3$
โ
My Approach
Using Hash Set of Squares
To efficiently check for the Pythagorean triplet, we use the following insight:
If $a^2 + b^2 = c^2$, then $c^2$ must be present in the array.
We can precompute the squares of all elements and store them in a hash set.
Then, iterate over all pairs $(a, b)$ in the array, compute $a^2 + b^2$, and check if this sum exists in the set.
Algorithm Steps:
Create a hash set
squares
that contains the square of every element inarr
.Iterate over all pairs
(arr[i], arr[j])
wherei < j
.For each pair, calculate
sum_squares = arr[i]^2 + arr[j]^2
.Check if
sum_squares
exists insquares
.If yes, return
true
immediately.
If no such triplet is found after checking all pairs, return
false
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(nยฒ), since we check all pairs
(i, j)
of elements in the array.Expected Auxiliary Space Complexity: O(n), as we store squares of all elements in a hash set.
๐งโ๐ป Code (C++)
class Solution {
public:
bool pythagoreanTriplet(vector<int>& arr) {
unordered_set<int> s;
for (int& x : arr) s.insert(x * x);
for (int i = 0; i < arr.size(); ++i)
for (int j = i + 1; j < arr.size(); ++j)
if (s.count(arr[i]*arr[i] + arr[j]*arr[j])) return true;
return false;
}
};
๐งโ๐ป Code (Java)
class Solution {
public boolean pythagoreanTriplet(int[] arr) {
HashSet<Integer> squares = new HashSet<>();
for (int x : arr) squares.add(x * x);
int n = arr.length;
for (int i = 0; i < n; ++i)
for (int j = i + 1; j < n; ++j)
if (squares.contains(arr[i]*arr[i] + arr[j]*arr[j])) return true;
return false;
}
}
๐ Code (Python)
class Solution:
def pythagoreanTriplet(self, arr):
s = set(x * x for x in arr)
n = len(arr)
for i in range(n):
for j in range(i + 1, n):
if arr[i]**2 + arr[j]**2 in s:
return True
return False
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated