educative.io

Educative

Pythagorean Triplets

vector<vector<int>> find_pythagorean_triplets(vector<int> arr) { 
  sort(arr.begin(), arr.end(), compare()); 
  vector<vector<int>> result; 
  int n = arr.size(); 
  for (int i = n -1; i >= 2;i--) { 
    int j = 0; 
    int k = i - 1; 
    while (j < k) { 
      int sqSum = arr[j] * arr[j] + arr[k] * arr[k]; 
      if (sqSum == arr[i] * arr[i]) { 
        result.push_back({arr[i],arr[j],arr[k]}); 
        j++; 
        k--; 
      } else if (sqSum < arr[i] * arr[i]) { 
        j++; 
      } else { 
        k--; 
      } 
    } 
  } 
  return result; 

struct compare { 
  bool operator()(int &A, int &B) { 
    if ((A * A) < (B * B)) { 
        return true; 
    } 
    return false; 
  } 
}; 

Is this code correct, I am getting correct triplets for the test case provided. but can you please check if it can work for more test cases.