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
squaresthat 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_squaresexists insquares.If yes, return
trueimmediately.
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++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 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