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).
 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 */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With