I have a quite difficult problem (perhaps even a NP-hard problem ^^) with looking for a solution in a massive collection of results. Perhaps there is an algorithm for it.
Below exercise is artificial but is a perfect example to illustrate my issue.
There is a big array with integers. Lets say it has 100.000 elements.
int numbers[] = {-123,32,4,-234564,23,5,....}
I want to check in a relatively quick way if a sum on any 2 numbers from this array is equal to 0. In other words, if the array has “-123” I want to find is there also a “123” number.
The easiest solution would be brute force – check everything with everything. That gives 100.000 x 100.000 a big number 😉 Obviously brute force method can by optimised. Order numbers and check negatives against positive only. My question is – is there something better then optimised brute force to find a solution?
The example you provided can be brute-force solved in
O(n^2)time.You can start ordering the numbers (
O(n·logn)) from smaller to bigger. If you place one pointer at the beginning (the “most negative number”) and other at the end (the “most positive”), you can check if there is such pair of numbers in an additionalO(n)steps by following the next procedure:Total complexity is
O(n·logn)+O(n) = O(n·logn).