Arrays & Strings · intermediate · ~15 min
Maintain two indices/pointers into one structure to scan in O(n).
'Two-pointer' refers to several patterns where two indices coordinate over a single sequence. The three flavours: converging (left + right, walk inward), same-direction (slow + fast, run at different speeds), and sliding window (left + right, both move forward, the window grows and shrinks).
Many problems that look like they need O(n log n) sorting or O(n^2) nested loops collapse to O(n) with two pointers. Cleanest cases: palindrome, cycle detection in linked lists, longest substring without repeats.
Converging. Start at both ends, decide direction at each step. Used in palindrome, 2-sum on sorted array, container-with-most-water.
Slow/fast (Floyd's tortoise & hare). Detect cycles in linked structures; find the middle of a list in one pass.
Sliding window. Maintain an invariant ('window contains no repeated chars'); shrink from the left when the invariant breaks.
Pentester mindset. Two-pointer is the building block of every fast string-search and pattern-detect routine in defensive scanners (anti-malware regex engines, log filters).
No special syntax — just two indices (size_t i, j;) and a loop.
Two-pointer is a family of algorithms where two indices walk a structure at coordinated speeds. Examples: palindrome check (converge from both ends), slow/fast cycle detection (Floyd), sliding-window substring problems.
int is_palindrome(const char *s){
size_t i = 0, j = strlen(s);
while (i < j) {
if (s[i] != s[--j]) return 0;
i++;
}
return 1;
}
/* slow/fast cycle detect */
node_t *slow = head, *fast = head;
while (fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if (slow == fast) return 1; /* cycle */
}
return 0;
Print both pointers/indices on every iteration; off-by-one is almost always at the meet point.
Pointer-to-pointer arithmetic must stay in bounds. For linked-list cycle detection, both slow and fast must be non-NULL before stepping fast twice.
Cycle detection in graphs, palindrome scanners, KMP-like pattern matchers, sliding-window log analysis, in-place array compaction.
Two pointers, one structure, coordinated steps. Converging, slow/fast, sliding window — three flavours, many problems.