Skip to content
Two Pointers — Explained with Examples

Two Pointers — Explained with Examples

DodaTech Updated Jun 15, 2026 2 min read

The two pointers technique uses two pointers to traverse data structure elements, often reducing time complexity from O(n²) to O(n).

Two pointers involves moving two indices through an array or list in a coordinated way. Common patterns include opposite direction (one from start, one from end — used in pair sum, palindrome checking) and same direction (both forward, one fast and one slow — used in linked list cycle detection, sliding window).

Think of two pointers like two people searching a long hallway. One starts at the left end, the other at the right. They meet in the middle after checking every aisle together. This is faster than one person walking the entire hallway alone and doubling back (nested loops).

The technique is simple but powerful. When you find yourself writing nested loops over the same array, consider whether two pointers can eliminate the inner loop.

# Two Sum II (sorted array) — opposite direction
def two_sum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        current = nums[left] + nums[right]
        if current == target:
            return [left, right]
        elif current < target:
            left += 1
        else:
            right -= 1
    return [-1, -1]

# Palindrome check — opposite direction
def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if s[left] != s[right]:
            return False
        left += 1
        right -= 1
    return True

# Remove duplicates from sorted array — same direction
def remove_duplicates(nums):
    if not nums:
        return 0
    slow = 0
    for fast in range(1, len(nums)):
        if nums[fast] != nums[slow]:
            slow += 1
            nums[slow] = nums[fast]
    return slow + 1

print(two_sum([2, 7, 11, 15], 9))  # [0, 1]
print(is_palindrome("racecar"))     # True

The two pointers pattern is especially effective on sorted arrays, linked lists, and string manipulation problems.

Sliding Window, Array, Linked List, Sorting Algorithms

Sliding Window Technique

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro