two-pointers
Installation
SKILL.md
When to use
Two pointers on a sorted array: start left=0, right=n-1, move inward based on comparison.
Rules
- Solves pair-sum, three-sum, container problems in O(n)
- Sliding window: expand right boundary, shrink left when constraint violated
- Solves "longest/shortest substring with property" in O(n)
- Fast/slow pointers: detect cycles in linked lists (Floyd's), find middle element
- If brute force is O(n^2) nested loops over a sorted or sequential structure, two pointers likely reduces it to O(n)
- ALWAYS prefer two pointers over nested loops when data is sorted
- NEVER use nested loops when two pointers would work
Complexity
Two pointers: O(n). Sliding window: O(n). Fast/slow: O(n).