← Home ← Codex ← DEBT
Browse by Category
+ added · updated 7d
← Back to glossary

Two-Pointer Technique

Algorithms Intermediate
debt(d7/e3/b3/t5)
d7 Detectability Operational debt — how invisible misuse is to your safety net

Closest to 'only careful code review or runtime testing' (d7). The detection_hints explicitly state 'automated: no' and describe the code_pattern as a nested loop on sorted data where a two-pointer O(n) solution would be better. No tool in the detection_hints list catches this; a reviewer must recognise the O(n²) pattern and realise two pointers apply. It won't cause a runtime error — just suboptimal performance — so it stays silent until load reveals it.

e3 Effort Remediation debt — work required to fix once spotted

Closest to 'simple parameterised fix' (e3). The quick_fix describes replacing a brute-force nested loop with a two-pointer traversal on a sorted array. This is more than a one-line swap (e1) since the loop logic must be restructured and sorting may need to be added, but it is contained within a single function or component and does not span multiple files.

b3 Burden Structural debt — long-term weight of choosing wrong

Closest to 'localised tax' (b3). The technique applies within a single algorithm/function scope. Once correctly implemented, it imposes no ongoing tax on the rest of the codebase — it is not a cross-cutting architectural choice. The applies_to contexts (web, cli) are broad, but the technique itself is scoped to individual functions solving specific problems.

t5 Trap Cognitive debt — how counter-intuitive correct behaviour is

Closest to 'notable trap' (t5). The misconception field states that developers believe two pointers only work on sorted arrays, missing fast/slow pointer and sliding window variants. The common_mistakes also list forgetting to sort first and incorrect pointer movement logic. These are documented gotchas that most developers encounter but are not catastrophically counterintuitive — they represent a narrower misunderstanding of scope rather than a fundamental behavioural inversion.

About DEBT scoring →

Also Known As

two-pointer approach Floyd's algorithm

TL;DR

An algorithmic pattern using two indices that move through a sorted array to find pairs or subarrays satisfying a condition in O(n) instead of O(n²).

Explanation

Two pointers typically start at opposite ends of a sorted array (or one at start, one ahead). By moving them based on comparison results, problems that would require nested loops become linear. Classic uses: finding a pair that sums to a target, removing duplicates from a sorted array, merging two sorted arrays. The fast/slow pointer variant (Floyd's algorithm) detects cycles in linked lists.

Diagram

flowchart TD
    ARR[Sorted array: 1 2 4 6 8 10<br/>Find pair summing to 10]
    subgraph TwoPointer
        L[Left pointer at 1]
        R[Right pointer at 10]
        CHECK{Sum = 11 > 10}
        CHECK -->|too big - move right left| R2[Right moves to 8<br/>1+8 = 9 < 10]
        R2 -->|too small - move left right| L2[Left moves to 2<br/>2+8 = 10 found!]
    end
    subgraph Complexity
        NAIVE[Naive O of n squared<br/>check all pairs]
        TP[Two pointer O of n<br/>one pass]
    end
style L fill:#1f6feb,color:#fff
style R fill:#d29922,color:#fff
style L2 fill:#238636,color:#fff
style NAIVE fill:#f85149,color:#fff
style TP fill:#238636,color:#fff

Common Misconception

Two pointers only work on sorted arrays — fast/slow pointers (cycle detection) and the sliding window variant work on unsorted data too.

Why It Matters

Turns O(n²) pair-finding problems into O(n), a common interview technique with real applications in database join algorithms and merge operations.

Common Mistakes

  • Not sorting the array first when the algorithm requires sorted input.
  • Moving both pointers by one each iteration — the correct move depends on which pointer's value is larger.
  • Off-by-one errors in the loop termination condition — use strict less-than for opposite-end pointers.
  • Forgetting that this technique requires sorted data for sum/target problems.

Code Examples

✗ Vulnerable
// O(n²) — nested loop to find pair summing to target:
function hasPairWithSum(array $arr, int $target): bool {
    for ($i = 0; $i < count($arr); $i++)
        for ($j = $i + 1; $j < count($arr); $j++)
            if ($arr[$i] + $arr[$j] === $target) return true;
    return false;
}
✓ Fixed
// O(n log n) sort + O(n) two-pointer = O(n log n) total:
function hasPairWithSum(array $arr, int $target): bool {
    sort($arr);
    $left = 0; $right = count($arr) - 1;
    while ($left < $right) {
        $sum = $arr[$left] + $arr[$right];
        if ($sum === $target) return true;
        $sum < $target ? $left++ : $right--;
    }
    return false;
}

Added 15 Mar 2026
Edited 30 May 2026
Views 53
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings T 0 pings W 1 ping T 0 pings F 0 pings S 0 pings S 0 pings M 1 ping T 0 pings W 3 pings T 1 ping F 1 ping S 0 pings S 1 ping M 0 pings T 1 ping W 0 pings T 1 ping F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 1 ping S 1 ping S 1 ping M 0 pings T 0 pings W
No pings yet today
No pings yesterday
Amazonbot 9 Perplexity 6 Scrapy 6 Ahrefs 4 Google 4 Unknown AI 3 PetalBot 3 Claude 2 Bing 2 ChatGPT 2 Meta AI 1 Sogou 1
crawler 38 crawler_json 4 pre-tracking 1
DEV INTEL Tools & Severity
🟡 Medium ⚙ Fix effort: Medium
⚡ Quick Fix
Use two pointers (start/end) on sorted arrays for problems requiring pairs — merge sorted arrays, find pairs summing to target, reverse in place; O(n) vs O(n²) brute force
📦 Applies To
any web cli
🔗 Prerequisites
🔍 Detection Hints
Nested loop on sorted array finding pairs; O(n²) solution for problem on sorted data where two pointers gives O(n)
Auto-detectable: ✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low False Positives: High ✗ Manual fix Fix: Medium Context: Function Tests: Update

✓ schema.org compliant