1. Two Pointers
When to use:
A two-pointer algorithm usually requires a linear data structure, such as an array or linked list.
Indicators that a problem may be solved with two pointers:
- The input is sorted (or can be sorted) β common for pair-sum, triplet problems.
- The problem involves merging or comparing two sequences (arrays, strings, lists).
- The problem requires removing duplicates or rearranging elements in-place.
- The problem asks for checking symmetry (e.g., palindromes).
- The solution can be framed as expanding/shrinking a "window" (sliding window problems).
When NOT to use:
Two pointers is not the right choice if:
- You need to count frequencies β use a hashmap or Counter instead.
- The problem involves graphs or trees (DFS/BFS are more suitable).
- You need subsets, permutations, or backtracking (recursion is required).
- The input is unsorted and order matters (sorting would break the logic).
- The problem is fundamentally divide & conquer (e.g., binary search, DP).
Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1] (because nums[0] + nums[1] = 2 + 7 = 9)
Why two pointers?
The array is sorted and weβre asked for a pair of values β move left/right pointers toward each other until sum = target.