Algorithms – Find All Pairs in an Array That Match a Condition

algorithms

Problem:

We have an int array[n]. We need to find all the pairs for which array[a] + array[b] = 0.

The only algorithm I came up with so far has O(n^2) – tho most obious one. Is there a better way to do it?

Best Answer

Sort your array, but maintain the original index number. Then you can loop through it once, each value can be instantly matched with the set of indexes stored against the matching point.

ie. loop through your array and store a key-value pair (where the key is array[n] and the value is n). A single iteration of this container will show you all matching indexes for the current value.