Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all pair of nos that sum up to S

Tags:

algorithm

Given an array, find all pair of nos that sum up to a given value. There is the classic O(n) algorithm of keeping 2 pointers at the front and back and bringing them closer to find the pair. This only leads to 1 pair. What if you want all pairs. Bonus: Find the minimum distance pair.

Can you do this in O(n).

like image 888
shreyasva Avatar asked Apr 07 '11 12:04

shreyasva


1 Answers

 int arr[SIZE]; /* sorted in ascending order */

 int a = 0, b = SIZE - 1, mindist = -1, sum;
 while (a < b) {
    sum = arr[a] + arr[b];
    if (sum == TARGET) { report_pair(a, b); mindist = b - a; a++ }
    else if (sum < TARGET) a++;
    else b--;
 }

 /* minimum distance stored in mindist */
like image 182
Antti Huima Avatar answered Oct 21 '22 06:10

Antti Huima