Lessons 6–10 · About 60 min per lesson

Sorting, two pointers and sliding windows

Exploit ordering or window properties to avoid scanning candidates repeatedly.

Lesson breakdown

  1. Lesson 6

    Find a target sum with two pointers on sorted values.

  2. Lesson 7

    Explain why a pointer move cannot skip a valid pair.

  3. Lesson 8

    Maintain a contiguous window under a sum limit in a nonnegative array.

  4. Lesson 9

    Show that each pointer moves at most n times.

  5. Lesson 10

    Build a negative-value counterexample and identify the failed window assumption.

Worked example

Find the longest contiguous segment of nonnegative [2,1,3,1] whose sum is at most 4.

How to solve it

Expand right and shrink left whenever the sum exceeds 4. [1,3] and [3,1] are valid length-2 segments, and every length-3 segment is too large.

Assignment

Implement the longest bounded window for a nonnegative array and compare with full interval enumeration.

Check your result

[0,0,1] with limit 0 → 2; [5] with limit 4 → 0; an empty array → 0.