PairSum problem Input: Array of numbers A of length n, number x. Output: true if for some indices i,j (not equal) we have x = A_i + A_j, otherwise false is returned. Exercise 2.3-7 is to find an algorithm to solve the PairSum problem in O(nlg(n)) time. My solution: PairSum(A,n,x) { 1. Sort A. 2. return PairSumSorted(A,n,x); } Correctness: PairSumSorted has the same output requirement as PairSum, while assuming A is sorted. Thus PairSum is correct if PairSumSorted is correct. I will show below that PairSumSorted is correct and runs in linear time (Theta(n)). Complexity: Step 1, sorting, can be done in Theta(nlg(n)), which dominates step 2. Thus PairSum runs in Theta(nlog(n)) as required for the problem. QED. PairSumSorted(A,n,x) Input: Array of numbers A of length n sorted in increasing order, number x. Output: true if for some indices i,j (not equal) we have x = A_i + A_j, otherwise false is returned. { 1. if (n < 2) then return false; 2. y := A_1 + A_n; 3. if (y == x) then return true; 4. if (y < x) then return PairSumSorted(A+1,n-1,x); 5. if (y > x) then return PairSumSorted(A,n-1,x); } Correctness: The result returned in step 1 or step 3 is clearly correct. Suppose the sum y is less than x. Every other sum involving A_1 is smaller (at least no larger), so we may remove A_1 from consideration. This is precisely what line 4 does. We similarly justify removing A_n from consideration in line 5. Runtime: Let T(n) be the cost for array of size n. We have, for some constant C, the recurrence T(1) <= C, and T(n) <= T(n-1) + C, for n > 1. This is because only one recursive call is made (in line 4 or 5) and the rest of the work is of constant amount. It is easy to see by induction that T(n) <= Cn: a) it is true for the base case n = 1. b) Using the inductive hypothesis, T(n-1) + C <= C(n-1) + C = Cn. Thus T(n) <= T(n-1) + C <= Cn.