top

Search

Software Key Tutorial

.

UpGrad

Software Key Tutorial

Pythagorean Triplet in an Array

Introduction

A set of three numbers known as a Pythagorean triplet proves the Pythagorean theorem, which asserts that the square of the hypotenuse (the side opposite the right angle) in a right-angled triangle is equal to the sum of the squares of the other two sides. Mathematically speaking, if the sides of a right-angled triangle are a, b, and c, then a2 b2 = c2.

Overview

Pythagorean triplet in an array formula can be found by looking for three elements that together make one triple. By determining if the squares of the first two elements added together equal the square of the third, these triplets can be recognised.

Pythagorean Triplet in an Array

Finding three elements in an array that make up a Pythagorean triplet is referred to as a Pythagorean triplet. The square of the hypotenuse, or side opposite the right angle, in a right-angled triangle, must equal the sum of the squares of the other two sides in order to satisfy the Pythagorean theorem.

These steps can be used to find Pythagorean triplets in an array:

1. Go through the array iteratively, choosing 'a' for the first entry.

2. Choose the second element as "b" after iterating over the other elements.

3. Determine the squares of "a" and "b" (a2 and b2, respectively).

4. Verify that the array contains the square sum of letters "a" and "b."

5. If it exists, we have discovered a Pythagorean triplet (a, b, c), where 'c' is the square root of the product of squares (sqrt(a2 b2)).

6. Carry out steps 2–5 for each 'a' and 'b' combination.

Here is an instance to demonstrate the procedure:

Think about the following array: [3, 5, 12, 13, 8, 10, 15]

1. Select 3 for letter "a."

2. Go through the remaining elements one more time, choosing 5 as "b."

3. Determine that a2 = 32 = 9 and b2 = 52 = 25.

4. Verify that the array has the squares' total (a2 b2 = 9 25 = 34). It isn't in this instance.

5. Select 12 as 'b' on the following element.

6 Determine b2 = 122 = 144 and a2 = 32 = 9.

7. Verify that the array contains the squares (a2 b2 = 9 144 = 153). It isn't in this instance.

8. Repeat the procedure for additional 'a' and 'b' pairings.

This allows you to loop through the array and spot any Pythagorean triplets that may be there.

Different Methods for Checking Pythagorean Triplet in an Array

There are various methods for checking pythagorean triplet in an array leetcode as listed below:

Method 1: Naive Approach

The simple method for determining Pythagorean triplet in an array example iterates through all possible arrangements of three elements using three stacked loops. We determine whether the third element's square is equal to the sum of the squares of the first two elements in each combination.

Here's an example to illustrate this approach:

def checkPythagoreanTriplets(arr):
    n = len(arr)
    for i in range(n):
        for j in range(i 1, n):
            for k in range(j 1, n):
                x = arr[i] * arr[i]
                y = arr[j] * arr[j]
                z = arr[k] * arr[k]
                if x == y z or y == x z or z == x y:
                    return True
    return False
arr = [3, 5, 12, 13, 8, 10, 15]
result = checkPythagoreanTriplets(arr)
print(result)  # Output: True

In the code above, we calculate the squares of all possible combinations of the three elements (i, j, and k). Then, we determine which of the three requirements for a Pythagorean triplet—x == y z, y == x z, or z == x y—is met. We return True, indicating the existence of a Pythagorean triplet, if any of the conditions are met. If not, we provide False.

However, this method is ineffective for big arrays because of the triple nested loops' O(n3) time complexity.

Method 2: Using Sorting

In this method, we sort the array in non-decreasing order. After sorting, we fix the largest element as 'c'. Then, using a two-pointer approach, we iterate over the remaining elements, considering them as 'a' and 'b'. We check if a² b² = c² holds true. This approach reduces the time complexity to O(n²).

Here's an example to demonstrate this method:

def checkPythagoreanTriplets(arr):
    n = len(arr)
    arr.sort()  # Sort the array in non-decreasing order
    for i in range(n-1, 1, -1):
        c = arr[i] * arr[i]
        left = 0
        right = i - 1
        while left < right:
            a = arr[left] * arr[left]
            b = arr[right] * arr[right]
            if a b == c:
                return True
            elif a b < c:
                left = 1
            else:
                right -= 1
    return False
arr = [3, 5, 12, 13, 8, 10, 15]
result = checkPythagoreanTriplets(arr)
print(result)  # Output: True

The array is sorted in the code above, and the largest element (c) is fixed by iterating from the end of the array. Two pointers, labeled "left" and "right," are initialized to point to the start and finish of the remaining components, respectively. We determine the squares of letters "a" and "b" and contrast them with the square of letters "c." We return True if a2 b2 equals c2. The left pointer is increased if a2 b2 c2, and the right pointer is decreased if a2 b2 > c2. This procedure is repeated until a triplet is discovered or all options have been explored.

Method 3: Using Hashing

Using hashing can provide an efficient approach to checking for Pythagorean triples program in C. We square each element and store them in a hash set. Then, for each pair of elements (a, b), we check if their sum of squares is present in the hash set.

Here's an example illustrating the hashing approach:

def checkPythagoreanTriplets(arr):
    n = len(arr)
    arr = [x * x for x in arr]  # Square each element
    set_arr = set(arr)  # Convert the array to a set for efficient lookup
    for i in range(n-1):
        for j in range(i 1, n):
            if arr[i] arr[j] in set_arr:
                return True
    return False
arr = [3, 5, 12, 13, 8, 10, 15]
result = checkPythagoreanTriplets(arr)
print(result)  # Output: True

Each element of the array is squared in the code above. The array is then changed into a set to facilitate quick search. Every pair of elements (a, b) is examined iteratively to see if their sum of squares (a2 b2) is present in the set. If it does, we give a result of True, indicating that a Pythagorean triplet exists. If not, we provide False.

Method 4: Using STL (Standard Template Library)

The STL algorithms can be used to streamline the search for Pythagorean triplet in Java if you are writing in a language like C . You may create clear code to address the issue by utilizing the std::set data structure and built-in tools like std::transform, std::accumulate, and std::any_of.

Here's an example in C using the STL:

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <numeric>
bool checkPythagoreanTriplets(const std::vector<int>& arr) {
    std::set<int> squaredSet;
    std::transform(arr.begin(), arr.end(), std::inserter(squaredSet, squaredSet.end()),
                   [](int num) { return num * num; });
    return std::any_of(arr.begin(), arr.end(), [&](int a) {
        return std::accumulate(arr.begin(), arr.end(), false, [&](bool res, int b) {
            return res || squaredSet.count(a * a b * b);
        });
    });
}
int main() {
    std::vector<int> arr = {3, 5, 12, 13, 8, 10, 15};
    bool result = checkPythagoreanTriplets(arr);
    std::cout << std::boolalpha << result << std::endl;  // Output: true
    return 0;
}

The std::transform technique is used in the code above to square each array element before inserting it into a set. Then, we iterate through each pair of elements to see if their total of squares is present in the set using std::any_of and std::accumulate. If a Pythagorean triplet is discovered, we return true, signifying its existence.

Method 5: An Improved Hashing-Based Method

By removing the explicit production of all potential pairs, this strategy improves the hashing-based method even more. Instead, we employ a nested loop to cycle through each pair, get their square sum, and determine whether they are present in the set.

Here is an illustration to show how this strategy works:

def checkPythagoreanTriplets(arr):
    n = len(arr)
    arr = [x * x for x in arr]  # Square each element
    set_arr = set(arr)  # Convert the array to a set for efficient lookup
    for i in range(n-1):
        for j in range(i 1, n):
            c_squared = arr[i] arr[j]
            if c_squared in set_arr:
                return True
    return False
arr = [3, 5, 12, 13, 8, 10, 15]
result = checkPythagoreanTriplets(arr)
print(result)  # Output: True

Similar to the previous hashing-based technique, we square each element of the array in this code and turn it into a set. Then, using nested loops, we repeatedly iterate through each pair rather than directly producing all potential pairs. We compute the square sum (c2) and determine whether it is present in the set. If a Pythagorean triplet is discovered, we return True, signifying its existence.

These techniques offer various strategies for searching for Pythagorean triples hackerrank solution in an array. The array's size and the programming language used are just two examples of variables that affect which method is selected.

Conclusion

We have looked at a variety of techniques for examining Pythagorean triples formula in an array. The naive method of employing nested loops, sorting the array, applying hashing techniques, utilizing the Standard Template Library (STL) in programming languages like C, and an optimized hashing-based method are some of these techniques. Each approach has advantages, and the best one to choose will depend on the particular conditions and limitations of the issue.

The naive method uses three nested loops and is ineffective for big arrays due to its time complexity of O(n3). The temporal complexity is reduced to O(n2) by sorting the array and applying a two-pointer strategy, offering a more effective solution. Sets are used to store squared elements in hash-based techniques, which, depending on the implementation, reach a time complexity of O(n2) or O(n).

The STL technique uses built-in functions in languages like C to produce short, simple code. It provides a simplified approach to resolving the issue. The efficiency of the optimized hashing-based method is increased because it does not generate all potential pairs.

FAQs

1. What is a Pythagorean triplet, question one?

A trio of numbers (a, b, and c) known as a Pythagorean triplet satisfy the formula a2 b2 = c2. The square of the hypotenuse, or side opposite the right angle, in a right-angled triangle, is equal to the sum of the squares of the other two sides.

2. How can Pythagorean triplets be found in an array?

Pythagorean triplets in an array can be found by iterating through the array and checking if any three elements satisfy the Pythagorean theorem. This involves calculating the square of each element, sorting the array, using hashing techniques, or leveraging the STL (in languages like C ) to efficiently identify the triplets.

3. What is the time complexity of checking Pythagorean triplets in an array?

The time complexity depends on the method used. The naive approach with nested loops has a time complexity of O(n^3). Sorting the array and using a two-pointer approach reduces it to O(n^2). Hashing-based methods can achieve either O(n^2) or O(n), depending on the specific implementation. The STL-based approach and optimized hashing-based approach also have time complexities of O(n^2) or O(n), respectively.

4. Can multiple Pythagorean triplets exist in a single array?

Yes, it is possible for multiple Pythagorean triplets to exist in a single array. The methods discussed can identify all the Pythagorean triplets present in the array.

5. Can the array contain negative or floating-point numbers for finding Pythagorean triplets?

The Pythagorean theorem and the methods discussed are applicable to positive integers. If the array contains negative or floating-point numbers, it may require additional considerations or modifications to adapt the methods accordingly.

Leave a Reply

Your email address will not be published. Required fields are marked *