Draw the pointers before coding
Updated
Before the loop, write the array and mark the starting indices: L=0 R=n-1, or i=0 w=0, or p=head q=head. Name the stop test. Then code the move that matches the drawing.
What to focus on
If the first drawing has both pointers on the left, you will write a trail. If they sit on the ends, you will write inward. Wrong drawing → wrong loop.
Worked examples
inward
a = [1, 4, 9], t=13- draw L under 1, R under 9
- stop L≥R
- move L if sum < t
Result: then write the loop
trail
a = [0, 1, 0, 9], keep nonzero- draw i and w under index 0
- stop i==n
- write then w++ or skip
Result: then write compact
two sequences
a = [1, 4, 9], b = [4, 7, 9]- draw i under a[0]=1, j under b[0]=4
- stop when either index hits length
Result: then write merge/intersect
Try it
Write drawStart(a). a is an array of integers. L and R are opposite-end indices, or i and w are same-direction, or i and j are two sequences. Print both starting pointers and the stop test, then the first line of the loop. Return nothing. For a = [1, 4, 9] t=13, a = [0, 1, 0, 9] compact, and merge of [1, 4, 9] with [4, 7, 9].
a is nonempty. Pair-sum a is sorted. Merge sequences are sorted.