JavaScript Snippet

Two-Pointer Template

Difficulty: Easy

The two-pointer technique is the linear-time answer to many sorted-array problems: pair sums, palindrome checks, in-place reversal, partition. This snippet covers the opposite-ends sweep for sorted-pair targets, the reverse-in-place pattern, and the slow-fast pointer used for in-place mutation. Each fits in 10 lines and runs in O(n) time, O(1) extra space.

Code Snippets
/

Two-Pointer Template

Two-Pointer Template

The two-pointer technique is the linear-time answer to many sorted-array problems: pair sums, palindrome checks, in-place reversal, partition. This snippet covers the opposite-ends sweep for sorted-pair targets, the reverse-in-place pattern, and the slow-fast pointer used for in-place mutation. Each fits in 10 lines and runs in O(n) time, O(1) extra space.

JavaScript
Easy
3 snippets
algorithms
two-pointers
code-template
arrays

418 views

3

When the array is sorted, the two-pointer sweep replaces the O(n^2) double loop with a single O(n) pass. The invariant is: every pair containing arr[lo] with an index < hi has already been considered, so if the current sum is too small, no smaller hi can help and we must move lo up. Symmetric reasoning lets us shrink hi when the sum is too large. Use this for twoSum on sorted input, finding pair-with-given-difference, or any problem that monotonically narrows on a sorted range.