Optimize the algorithm suggested above
Anonimo
First sort the array, it costs O(n log(n)). With sorted array, to find any 2 elements whose sum equal to S (S could be any number) cost linear time O(n). Then for any element in the array Xi, set S = -Xi, and remove Xi from the array. Then do the "2 elements sum to S" problem with the modified array with total cost of O(n). Then all the results plus Xi equal to zero. The total cost will be: sorting O(n log(n)). For each Xi: need O(n), and all Xi, O(n^2). Algorithm to find sum of 2 elements equal to S in linear time: (assume there are no two elements that are equal to each other) int L = 0; int H = nElements-1; // last element of the array while (L S) { H--; } else if (A[L] + A[H] == S) { output(L, H); L ++; } }