Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to sum a triple?

We have an array A with m positive integer numbers, what's an algorithm that will

return true if there's a triple (x,y,z) in A such that A[x] + A[y] + A[z] = 200

Otherwise return false. Numbers in array are distinct and running time must be O(n).

I came up with O(n^3). Any ideas on how to achieve this with O(n)?

like image 348
33ted Avatar asked Jun 23 '26 19:06

33ted


1 Answers

Since elements are unique, this boils down to pre processing the array in O(n) to filter redundant elements - which are larger than 200 (none of them will be in the triplet).

Than, you have an array which its size is no larger than 200.

Checking all triplets in this array is O(200^3)=O(1) (it can be done more efficiently in terms of constants though).

So, this will be O(n) U O(200^3) = O(n)

like image 86
amit Avatar answered Jun 25 '26 16:06

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!