8

I was trying to solve the pair sum problem, i.e., given a sorted array, we need to if there exist two indices i and j such that i!=j and a[i]+a[j] == k for some k.

One of the approaches to do the same problem is running two nested for loops, resulting in a complexity of O(n*n).

Another way to solve it is using a two-pointer technique. I wasn't able to solve the problem using the two-pointer method and therefore looked it up, but I couldn't understand why it works. How do I prove that it works?

#define lli long long
 //n is size of array
bool f(lli sum) {
    int l = 0, r = n - 1;
    while ( l < r ) {
       if ( A[l] + A[r] == sum ) return 1;
       else if ( A[l] + A[r] > sum ) r--;
       else l++;
    }
    return 0;
}
8
  • You should show us what you have done till now for us to be able to tell you what went wrong! Jan 30, 2018 at 6:32
  • I am not able to even start with something logical.
    – Anjkhade
    Jan 30, 2018 at 6:34
  • 2
    I wasn't able to solve the problem using two pointer method.. You should show us whatever you have done. The sorting and then the traversal of the list using start and end pointers. Jan 30, 2018 at 6:38
  • 1
    Also you should choose one language. C or C++ ? Jan 30, 2018 at 6:39
  • Two pointer approach is applicable to sorted array. You have not specified is your array sorted or not.
    – MBo
    Jan 30, 2018 at 6:39

2 Answers 2

22

Well, think of it this way:

You have a sorted array (you didn't mention that the array is sorted, but for this problem, that is generally the case):

{ -1,4,8,12 }

The algorithm starts by choosing the first element in the array and the last element, adding them together and comparing them to the sum you are after.

If our initial sum matches the sum we are looking for, great!! If not, well, we need to continue looking at possible sums either greater than or less than the sum we started with. By starting with the smallest and the largest value in the array for our initial sum, we can eliminate one of those elements as being part of a possible solution.

Let's say we are looking for the sum 3. We see that 3 < 11. Since our big number (12) is paired with the smallest possible number (-1), the fact that our sum is too large means that 12 cannot be part of any possible solution, since any other sum using 12 would have to be larger than 11 (12 + 4 > 12 - 1, 12 + 8 > 12 - 1).

So we know we cannot possibly make a sum of 3 using 12 + one other number in the array; they would all be too big. So we can eliminate 12 from our search by moving down to the next largest number, 8. We do the same thing here. We see 8 + -1 is still too big, so we move down to the next number, 4, and voila! We find a match.

The same logic applies if the sum we get is too small. We can eliminate our small number, because any sum we can get using our current smallest number has to be less than or equal to the sum we get when it is paired with our current largest number.

We keep doing this until we find a match, or until the indices cross each other, since, after they cross, we are simply adding up pairs of numbers we have already checked (i.e. 4 + 8 = 8 + 4).

This may not be a mathematical proof, but hopefully it illustrates how the algorithm works.

4
  • 1
    That's exactly what I was looking for. A big thanks to you Sir.
    – Anjkhade
    Jan 30, 2018 at 7:04
  • 1
    Glad it helped, I recently went through this algorithm to understand how it works too. Jan 30, 2018 at 7:08
  • Great explanation! I'm seeing a lot of programming interview problems that can be solved in a similar fashion (for example this one [leetcode.com/problems/container-with-most-water]). I'm having generalizing this rule though to problems like the container one, can you help?
    – zzzzzzz
    Jan 14, 2019 at 2:19
  • @zzzzzzz, I tried to answer with more mathematical rigor. Hope that helps you generalize the solution to the problem you mentioned.
    – Palec
    Jul 4, 2022 at 17:55
1

Stephen Docy made a great job tracing the program's execution and explaining the rationale behind its decisions. Maybe making the answer closer to a mathematical proof of the algorithm's correctness could make it easier to generalize to problems like the one mentioned by zzzzzzz in the comments.

We are given a sorted array A of length n and an integer sum. We need to find if there are any two indices i and j such that i != j and A[i] + A[j] == sum.

The solutions (i, j) and (j, i) are equivalent, so we can assume that i < j without loss of generality. In the program, the current guess at i is called l and the current guess at j is called r.

We iteratively slice the array till we find a slice that has the two summands that sum to sum at its boundary, or we find there is no such slice. The slice starts at index l and ends at index r and I will write it as (l, r).

Initially, the slice is the whole array. In each iteration, the length of the slice is decreased by 1: either the left boundary index l increases or the right boundary index r decreases. When the slice length decreases to 1 (l == r), there are no pairs of different indexes inside the slice, so false is returned. This means that the algorithm halts for any input. The O(n) complexity is also immediately clear. The correctness remains to be proven.

We can assume there is a solution; if there is none, the analysis in the above paragraph applies and the branch returning true can never be executed.

The loop has an invariant (statement that holds true regardless of how many iterations have been done yet): When a solution exists, it is either (l, r) itself or its sub-slice. Mathematically, such an invariant is a lemma -- something that is not very useful by itself but makes a stepping stone in the overall proof. We get the overall correctness by initially making (l, r) the whole array and observing that as each iteration makes the slice shorter, the invariant ensures that we will eventually find the solution. Now, we just need to prove the invariant.

We will prove the invariant by induction. The induction base is trivial -- the initial slice (l, r) either is the solution, or contains it as a sub-slice. The hard part is the induction step, i.e. proving that when (l, r) contains the solution, either it is the solution itself or the slice for the next iteration contains the solution as a sub-slice.

  1. When A[l] + A[r] == sum, (l, r) is the solution itself; the first condition in the loop is triggered, true is returned, and everyone is happy.

  2. When A[l] + A[r] > sum, the slice for the next iteration is (l, r - 1), which still contains the solution. Let's prove that by contradiction, assuming (l, r - 1) does not contain the solution. How could that happen, when (l, r) contained the solution (by induction hypothesis)? The only way would be that the solution (i, j) has j == r (r is the only index we removed from the slice). Because by definition A[i] + A[j] == sum, we get A[i] + A[r] == sum < A[l] + A[r] in this branch. When we subtract A[r] from both sides of the inequality, we get A[i] < A[l]. But A[l] is the smallest value in the (l, r) slice (the array is sorted), so this is a contradiction.

  3. When A[l] + A[r] < sum, the slice for the next iteration is (l + 1, r). The argument is symmetric to the previous case.


The algorithm may be easily rewritten as recursive, which simplifies the analysis at the expense of actual performance. This is the functional programming approach.

#define lli long long
//n is size of array
bool f(lli sum) {
    return g(sum, 0, n - 1);
}
bool g(lli sum, int l, int r) {
    if ( l >= r ) return 0;
    else if ( A[l] + A[r] == sum ) return 1;
    else if ( A[l] + A[r] > sum ) return g(sum, l, r - 1);
    else return g(sum, l + 1, r);
}

The f function still contains the initialization, but it calls the new g function, which implements the original loop. Instead of keeping the state in local variables, it uses its parameters. Each call of the g function corresponds to a single iteration of the original loop.

The g function is a solution to a more general problem than the original one: Given a sorted array A, are there any two indices i and j such that i != j and A[i] + A[j] == sum and both i and j are between l and r (inclusive)?

This makes reading the analysis even simpler. The loop invariant is actually the proof of correctness of g and the structure of g guides the proof.

1
  • The leetcode.com/problems/container-with-most-water problem may be approached in the same way. The tricky part is that g() is no longer a boolean function; it accepts an extra integer and returns an integer. The integer is the current maximum. The argument in the induction step is about realizing that 1. the lower of the two heights is the current surface level and upper bound on any future surface level while the width only decreases and that 2. each height outside the current slice has already been abandoned and at that moment, it was the surface level for a larger width.
    – Palec
    Jul 4, 2022 at 18:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.