Module 2 · Beginner · Arrays, strings and hashing

The two pointers technique, with Python examples

The two pointers technique explained: pointers from both ends or in one direction, pair sum in a sorted array, remove duplicates and most water, in O(n).

By theprogrammers team · · 7 min read

The two pointers technique uses two index variables that move through a list, instead of one loop inside another. It turns many O(n²) problems into O(n), usually with O(1) extra space, which is why it's one of the first patterns interviewers test.

This lesson explains the two main styles, pointers moving towards each other and pointers moving in the same direction, and solves the classic problems for each.

The idea

A "pointer" here is just an integer that holds a position in a list, such as left = 0. Instead of checking every pair of positions with nested loops, you move two pointers in a smart way, so that each step rules out many pairs at once. Each pointer moves at most n times, so the whole thing is O(n).

Style 1: pointers from both ends

Start one pointer at the beginning and one at the end, and move them towards each other until they meet. This works best on sorted data, or on problems about symmetry.

Pair with a target sum in a sorted list

Given a sorted list, find two numbers that add up to a target.

def pair_sum(nums, target):
    left, right = 0, len(nums) - 1
    while left < right:
        total = nums[left] + nums[right]
        if total == target:
            return [left, right]
        if total < target:
            left += 1        # need a bigger sum
        else:
            right -= 1       # need a smaller sum
    return []

print(pair_sum([1, 3, 4, 6, 8, 11], 10))    # [2, 3]: 4 + 6

Why is it safe to move a pointer? If the sum is too small, then nums[left] paired with any number up to nums[right] is also too small, because the list is sorted. So nums[left] can't be part of the answer, and we move past it. Each step throws away one number for good.

Trace it with target 10:

leftrightSumAction
0 (1)5 (11)12Too big: right moves left
0 (1)4 (8)9Too small: left moves right
1 (3)4 (8)11Too big: right moves left
1 (3)3 (6)9Too small: left moves right
2 (4)3 (6)10Found

O(n) time, O(1) space. The hash map version of two sum works on unsorted data but needs O(n) space.

Valid palindrome

Is a string the same forwards and backwards, ignoring case and anything that isn't a letter or digit?

def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():
            left += 1
        elif not s[right].isalnum():
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False
        else:
            left += 1
            right -= 1
    return True

print(is_palindrome("A man, a plan, a canal: Panama"))    # True

The pointers skip punctuation and compare matching characters from the outside in.

Container with most water

Given heights of vertical lines, find two lines that, with the x-axis, hold the most water.

The water held is the shorter height × the distance between the lines.

def max_water(heights):
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        width = right - left
        best = max(best, min(heights[left], heights[right]) * width)
        if heights[left] < heights[right]:
            left += 1
        else:
            right -= 1
    return best

print(max_water([1, 8, 6, 2, 5, 4, 8, 3, 7]))    # 49

Why move the shorter line? The width shrinks with every move, so the only hope of more water is a taller limiting line. Moving the taller one can never help, because the shorter one still limits the height.

Style 2: pointers in the same direction

Both pointers start at the beginning. A fast pointer reads every item; a slow pointer marks where the next item to keep should go. This is perfect for changing a list in place.

Remove duplicates from a sorted list

Remove duplicates in place and return the number of unique values.

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

a = [1, 1, 2, 3, 3, 3, 4]
k = remove_duplicates(a)
print(k, a[:k])    # 4 [1, 2, 3, 4]

slow points at the last unique value written. When fast finds a new value, it's copied just after it. The move zeros problem uses the same pattern.

Merge two sorted lists

One pointer in each list, always taking the smaller value:

def merge(a, b):
    i = j = 0
    result = []
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            result.append(a[i])
            i += 1
        else:
            result.append(b[j])
            j += 1
    result.extend(a[i:])
    result.extend(b[j:])
    return result

print(merge([1, 4, 7], [2, 3, 8, 9]))    # [1, 2, 3, 4, 7, 8, 9]

O(n + m). This is the heart of merge sort.

Three numbers: sort first, then two pointers

Find all unique triples that sum to zero.

The brute force is O(n³). Sort the list, fix one number, then use two pointers on the rest for the other two: O(n²).

def three_sum(nums):
    nums.sort()
    result = []
    for i in range(len(nums) - 2):
        if i > 0 and nums[i] == nums[i - 1]:
            continue                       # skip duplicate first numbers
        left, right = i + 1, len(nums) - 1
        while left < right:
            total = nums[i] + nums[left] + nums[right]
            if total < 0:
                left += 1
            elif total > 0:
                right -= 1
            else:
                result.append([nums[i], nums[left], nums[right]])
                left += 1
                while left < right and nums[left] == nums[left - 1]:
                    left += 1              # skip duplicate second numbers
    return result

print(three_sum([-1, 0, 1, 2, -1, -4]))    # [[-1, -1, 2], [-1, 0, 1]]

Sorting first is a common move: it costs O(n log n) but unlocks two pointers.

How to recognise a two pointers problem

  • The input is a sorted list, or sorting it would help.
  • You're looking for a pair (or triple) that meets a condition.
  • The problem asks you to modify a list in place with O(1) extra space.
  • The problem involves symmetry: palindromes, reversing.
  • You're merging two sorted sequences.

When the problem is about a range of consecutive items instead, reach for the related sliding window technique.

Practice

  1. Given a sorted list, return a sorted list of the squares. [-4, -1, 0, 3, 10] gives [0, 1, 9, 16, 100]. Do it in O(n).
Show the answer

The largest squares are at the ends. Compare both ends and fill the result from the back:

def sorted_squares(nums):
    left, right = 0, len(nums) - 1
    result = [0] * len(nums)
    for pos in range(len(nums) - 1, -1, -1):
        if abs(nums[left]) > abs(nums[right]):
            result[pos] = nums[left] ** 2
            left += 1
        else:
            result[pos] = nums[right] ** 2
            right -= 1
    return result

print(sorted_squares([-4, -1, 0, 3, 10]))    # [0, 1, 9, 16, 100]
  1. Reverse only the vowels of a string: "hello" becomes "holle".
Show the answer
def reverse_vowels(s):
    chars = list(s)
    vowels = set("aeiouAEIOU")
    left, right = 0, len(chars) - 1
    while left < right:
        if chars[left] not in vowels:
            left += 1
        elif chars[right] not in vowels:
            right -= 1
        else:
            chars[left], chars[right] = chars[right], chars[left]
            left += 1
            right -= 1
    return "".join(chars)

print(reverse_vowels("hello"))    # holle
  1. Is s a subsequence of t? (Its letters appear in t in order, not necessarily together.) "ace" is a subsequence of "abcde".
Show the answer
def is_subsequence(s, t):
    i = 0
    for ch in t:
        if i < len(s) and s[i] == ch:
            i += 1
    return i == len(s)

One pointer in each string: O(len(t)).

Interview questions

What is the two pointers technique?

Using two indexes that traverse a sequence, either from both ends towards each other or in the same direction at different speeds, to avoid nested loops. It typically gives O(n) time and O(1) space.

Why does two pointers on a sorted array find a pair sum correctly?

If the sum is too small, the left element can't pair with any remaining element (all are ≤ the right one), so it's safe to discard it; symmetrically for too large. Each step discards one candidate without missing a valid pair.

When would you choose a hash map over two pointers for two sum?

When the array is unsorted and you need original indexes: the hash map is O(n) time and O(n) space. Sorting for two pointers costs O(n log n) and loses positions unless you track them.

What to learn next

  1. Handle ranges of consecutive items with the sliding window technique.
  2. Compare with the hash map approach in hash maps for coding problems.