GATE / CS ARCHIVE

GATE CSE 1994 / QUESTION 25

Two pointers for a sorted pair sum

Algorithms · Searching, Sorting & Selection · Full GATE CSE 1994 paper

GATE 1994, Q25 5 marks · Descriptive
Report issue

Searching, Sorting & Selection

Question 25, GATE 1994: An integer array satisfies A[1]≤A[2]≤…≤A[n]. Give Pascal-like linear-time pseudocode to find indices i,j with A[i]+A[j]=M if a pair exists. State how equal indices are treated.
Tap to enlarge
Answer & solution

Answer: Start i=1,j=n; advance i if sum<M, decrease j if sum>M, return at equality. Use i<j for distinct indices, i≤j if reuse is allowed. (no official key was published)

For distinct array positions, use: i:=1; j:=n; found:=false; while (i<j) and not found do begin s:=A[i]+A[j]; if s=M then found:=true else if s<M then i:=i+1 else j:=j−1 end; if found then output(i,j) else output('no pair'). A return statement at equality is an equivalent formulation. Use an arithmetic type wide enough to avoid overflow in the sum.

The invariant is that any still-possible pair lies entirely within the index interval [i,j]. If A[i]+A[j]<M, then A[i]+A[k]≤A[i]+A[j]<M for every k≤j in that interval. Therefore no candidate using i works, and discarding i is safe. If the sum exceeds M, then A[k]+A[j]≥A[i]+A[j]>M for all remaining k≥i, so discarding j is safe. Equality supplies a valid witness immediately. These arguments use nondecreasing order and therefore also cover duplicates and negative integers.

Each unsuccessful iteration shortens the interval by one; there are at most n−1 such iterations, giving O(n) time and O(1) auxiliary space. Empty and single-element arrays have no distinct-position pair.

The source does not explicitly require i≠j. If reusing a single position is permitted, change the loop condition to i≤j. The same elimination proof then includes the diagonal pair when 2A[i]=M. Keeping this variant explicit prevents silently rejecting a valid pair under that interpretation.

Original paper, page 7