Skip to content

Module 18 · Algorithms and Problem Solving — topic 17 of 18

Two-pointer techniques

Solving array and string problems with two indexes: pointers moving towards each other (palindromes, pair sums in sorted data), read/write pointers for in-place changes, merging sorted lists, and sliding windows.

Beginner 10 min read·Lesson 277 of 306 in Python Programming

Learning objectives

  • Use opposite-end pointers on sorted data and strings
  • Use read and write pointers to modify lists in place
  • Merge sorted lists and apply sliding windows

Definition

The two-pointer technique uses two indexes that move through a sequence in a coordinated way — from both ends towards the middle, or both forwards at different speeds — to solve problems in linear time and constant extra space.

Introduction

Checking a palindrome by comparing the first and last letters, then moving inwards, is the simplest two-pointer algorithm. The same idea solves surprisingly many problems.

Why it matters

Two pointers often replace an O(n²) pair-checking loop with a single O(n) pass and no extra memory.

Detailed explanation

Opposite-direction pointers start at both ends (i = 0, j = len − 1) and move towards each other until they meet.

On sorted data, the sum of a[i] + a[j] tells you which pointer to move: too small, move i right; too large, move j left. Each step discards one candidate, giving O(n).

Same-direction pointers move forwards at different times: a read pointer scans every element while a write pointer marks where the next kept element goes, allowing in-place filtering.

Merging two sorted lists uses one pointer per list, always taking the smaller current element.

A sliding window keeps a range [left, right) and updates a running total as it moves, instead of recomputing each window.

These techniques usually require sorted input or a property that makes moving a pointer safe.

Draw the pointers on paper for a small example; off-by-one mistakes at the boundaries are the most common bugs.

Merge sort's merge step and many string algorithms are built on these patterns.

Syntax

Python
i, j = 0, len(a) - 1
while i < j:
s = a[i] + a[j]
if s == target:
break
if s < target:
i += 1
else:
j -= 1
  • Pointers from both ends, or both forwards.
  • Each step discards candidates.
  • O(n) time, O(1) space.

Code examples

Palindrome check

Python
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
print(is_palindrome("level"), is_palindrome("python"))
Output
True False

Pair sum in sorted data

Python
def pair_sum_sorted(nums, target):
i, j = 0, len(nums) - 1
while i < j:
s = nums[i] + nums[j]
if s == target:
return nums[i], nums[j]
if s < target:
i += 1
else:
j -= 1
return None
print(pair_sum_sorted([1, 3, 4, 6, 8, 11], 10), pair_sum_sorted([1, 2, 3], 10))
Output
(4, 6) None

More examples

In-place dedupe, merging and a sliding window

Python
def dedupe_sorted(nums):
if not nums:
return 0
write = 1
for read in range(1, len(nums)):
if nums[read] != nums[write - 1]:
nums[write] = nums[read]
write += 1
del nums[write:]
return write
def merge(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out + a[i:] + b[j:]
def max_window_sum(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
a = [1, 1, 2, 3, 3, 3, 4]
print(dedupe_sorted(a), a)
print(merge([1, 4, 9], [2, 3, 10, 12]))
print(max_window_sum([2, 1, 5, 1, 3, 2], 3))
Output
4 [1, 2, 3, 4]
[1, 2, 3, 4, 9, 10, 12]
9

Step-by-step explanation

  • The read pointer visits every element; the write pointer advances only when a new value is found.
  • merge always takes the smaller front element, then appends whatever remains.
  • The window sum adds the element entering and subtracts the one leaving, so each window costs O(1).

Expected output

Running “In-place dedupe, merging and a sliding window” prints exactly:

TextOutput
4 [1, 2, 3, 4]
[1, 2, 3, 4, 9, 10, 12]
9

Practical applications

  • Merging sorted log files by timestamp.
  • Finding the best stretch of days for sales or temperature.

Best practices

  • Check whether the input must be sorted.
  • Trace pointers on a small example.
  • Prefer two pointers over nested loops for pair problems on sorted data.

Common mistakes

Two pointers on unsorted data

Avoid

pair_sum_sorted([8, 1, 11, 4], 12)

Prefer

pair_sum_sorted(sorted([8, 1, 11, 4]), 12)

Moving pointers based on the sum only makes sense when the data is sorted.

Important notes

  • Fast and slow pointers (one moving twice as fast) detect cycles in linked structures.

Key takeaways

  • Opposite pointers solve palindrome and sorted pair problems.
  • Read/write pointers modify lists in place.
  • Merging and sliding windows are two-pointer patterns.

Try it yourself

  1. 1
    Move all zeros in a list to the end in place, keeping the order of other elements.
  2. 2
    Find the length of the longest substring without repeating characters using a sliding window.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic