geeksforgreeks:Pythagorean Triplet in an array

Given an array of integers, write a function that returns true if there is a triplet (a, b, c) that satisfies a2 + b2 = c2.
Example:
Input: arr[] = {3, 1, 4, 6, 5}
Output: True
There is a Pythagorean triplet (3, 4, 5).

Input: arr[] = {10, 4, 6, 12, 5}
Output: False
There is no Pythagorean triplet.


Solution:

https://www.geeksforgeeks.org/find-pythagorean-triplet-in-an-unsorted-array/
1) do square of each element in input array.
2) sort squared array in increasing order, this take O(nlogn)
3) to find triple (a, b, c), so that a2 = b2 + c2.

     1. fix a as the last element of the array.
     2. search a pair(b,c) in the subarray between first element and 'a'. a pair(b,c) with given sum can be found in o(n) using middle algorithm.
     3. if no pair found for current 'a',  move a one left and repeat 2,3


 public boolean isTriplet(int arr[]) 
    {
  int n = arr.length;
  Arrays.sort(arr);
  for(int i = 0; i < n; i++) {
   arr[i] = arr[i] * arr[i];
  }
  
  for(int i = n - 1; i >= 2; i--) {
   int r = i - 1;
   int l = 0;
   while( l < r) {
    if( arr[r] + arr[l] == arr[i]) {
     return true;
    }else if( arr[r] + arr[l] < arr[i]) {
     l++;
    }else {
     r--;
    }
   }
  }
  return false; 
    
    }




Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal