Back to Articles
DSA8 min readJun 11, 2026

Mastering Two Pointers

Learn how to optimize linear search intervals and matching bounds from O(N^2) to O(N) using inward or different speed pointers.

The Two Pointers pattern is one of the most efficient techniques to process sorted arrays or lists. By maintaining two index variables that traverse the collection concurrently, we can eliminate nested loops and perform checks in linear time.

Inward-Moving Pointers (Sorted Arrays)

When an array is sorted, we can initialize one pointer at the start (0) and another at the end (len - 1). Depending on the sum or conditions, we increment the left pointer or decrement the right pointer to narrow search bounds.

javascriptEditor
function twoSumSorted(nums, target) {
    let left = 0;
    let right = nums.length - 1;
    
    while (left < right) {
        const currentSum = nums[left] + nums[right];
        if (currentSum === target) {
            return [left + 1, right + 1]; // 1-based indexing
        } else if (currentSum < target) {
            left++;
        } else {
            right--;
        }
    }
    return [];
}

Fast & Slow Pointers (Linked Lists)

In cyclic structures or linked lists, we can move one pointer twice as fast as the other (Fast = 2x, Slow = 1x). If a cycle exists, the fast pointer will eventually catch up and meet the slow pointer.

Want to play with this concept?

We build interactive visual terminals for tokenizers, rendering engines, rate limiters, and network topologies. Explore them live!

Open Interactive Labs →