Pythagorean Triplets

You are given an array of n integers (a1, a2,....,an), you need to find if the array contains a pythagorean triplet or not.

An array is said to have a pythagorean triplet if there exists three integers x,y and z in the array such that x^2 + y^2 = z^2.

Note
1. The integers x,y and z might not be distinct , but they should be present at different locations in the array i.e if a[i] = x, a[j] = y and a[k] = z, then i,j and k should be pairwise distinct.
2. The integers a,b and c can be present in any order in the given array.
Input Format:
The first line contains a single integer t -  the number of test cases. Each test case consists of 2 lines as follows:
The first  line of each test case will contain the integer n, denoting the total number of elements in the array.
The second line of each test case will contain n space-separated integers a1,a2,....,an ,  where ai is the ith element of the array..
Output Format:
For each test case, print “yes”, if the array contains a pythagorean triplet,”no” otherwise.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <=  T <= 10
3 <=  N <= 10^3
1 <= a[i] <= 10^4 

Time Limit: 1sec
CodingNinjas
author
2y

Approach :
1) I solved it in O(N^2) approach.
2) Sort the array.
3) Initially map all the elements of the array to their index in a Hash Map or a Hash Set.
4) Now , run 2 for loops and for every x^2 + y^2...read more

CodingNinjas
author
2y
Brute Force
  • One simple naive solution is to try every possible triplet present in the array as a candidate for the pythagorean triplet.
  • So, we simply run three nested loops, and pick three integers and ...read more
CodingNinjas
author
2y
HASHMAP
  • Let us assume that the maximum element in the array is ‘mx’, now we know that if there is a valid pythagorean triplet (a,b,c) in the array , then a<=mx, b<=mx, and c<=mx.
  • Thus, we can iterate ov...read more
CodingNinjas
author
2y
Sorting
  • Before jumping into the actual solution , let us observe few things:
  1. Given two integers a1 and a2 such that a1
  2. According to the property: a^2 + b^2 = c^2, it is obvious that...read more
Add answer anonymously...
Ernst & Young Associate Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter