How to find pythagorean triplets in an array faster than O(N^2)?

I understand this question as

Given an array, find all such triplets i,j and k, such that a[i]2 = a[j]2+a[k]2

The key idea of the solution is:

  • Square each element. (This takes O(n) time). This will reduce the original task to “find three numbers in array, one of which is the sum of other two”.

Now it you know how to solve such task in less than O(n2) time, use such algorithm. Out of my mind comes only the following O(n2) solution:

  1. Sort the array in ascending order. This takes O(n log n).
  2. Now consider each element a[i]. If a[i]=a[j]+a[k], then, since numbers are positive and array is now sorted, k<i and j<i.

    To find such indexes, run a loop that increases j from 1 to i, and decreases k from i to 0 at the same time, until they meet. Increase j if a[j]+a[k] < a[i], and decrease k if the sum is greater than a[i]. If the sum is equal, that’s one of the answers, print it, and shift both indexes.

    This takes O(i) operations.

  3. Repeat step 2 for each index i. This way you’ll need totally O(n2) operations, which will be the final estimate.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)