Advanced Problem Solving and Revision

Lesson 20 of 20

Two pointers converge on a hidden pair sum, then a sliding window sweeps the best stretch in a single O(n) pass.

The big picture

The pattern toolkit

The final lap is a revision of the templates that crack most interview warm-ups: converging pointers, sliding windows, prefix sums and two bit tricks.

Pattern first, code second

The real skill is naming the template within seconds of reading a problem: sorted array → two pointers, contiguous run → sliding window, range sums → prefix.

Two pointers

Start both ends of a SORTED array. Every comparison retires one element forever: 6 comparisons here beat the 28 checks of a nested loop.

Sliding window

Keep a running sum and update it in O(1) per slide: sum += a[i] - a[i-k]. Brute force re-adds k elements for every one of the n-k windows.

Prefix sums

pre[i] = sum of the first i elements. Any range sum collapses to pre[r+1] - pre[l] after one O(n) build — 14 - 4 = 10 for a[2..4].

Bit tricks

n & (n-1) clears the lowest set bit: 12 & 11 = 8. When the result is 0, n was a power of two: 16 & 15 = 0.