1. Home

A Comprehensive Guide on Software Key Tutorials

Elevate your software skills with our comprehensive tutorials covering concepts from basic to advanced techniques. Dive in and become a software pro!

• 220 Lessons
• 37 Hours
159.Â

# Pythagorean Triplet in an Array

Updated on 19/07/20241,921 Views

## 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 Falsearr = [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 Falsearr = [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 Falsearr = [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 Falsearr = [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.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working â€¦Read More

###### Get Free Career Counselling
+91
*
By clicking, I accept theT&Cand
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.

Talk to our experts. Weâ€™re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...