Data Structures18 min read

Two Pointer Technique

Solve array/list problems efficiently using two pointers: pairs, removing duplicates in sorted data, and sliding comparisons with clear visuals.

David Miller
September 23, 2025
7.9k186

Two pointers is a technique used with lists (often sorted).

Idea:

  • you keep two indexes moving
  • you avoid nested loops
  • you make code faster

Example: find pair with sum in sorted list

def has_pair(nums, target):
    left, right = 0, len(nums) - 1

    while left < right:
        s = nums[left] + nums[right]
        if s == target:
            return True
        if s < target:
            left += 1
        else:
            right -= 1

    return False

print(has_pair([1,2,3,4,6,8], 10))  # True (2+8)

Why this is powerful

Instead of checking all pairs (slow), you move pointers smartly.

Graph: pointer movement

flowchart LR
  A[left] --> B[move right if sum too small]
  C[right] --> D[move left if sum too big]

Remember

  • Works best on sorted lists
  • Often replaces O(n²) with O(n)
  • Very common in interviews and real code
#Python#Intermediate#Techniques