Coding Pattern:

Two Pointers

This pattern has an earnable cheat sheet.

Pattern concept

Step 1 of 11
Two Pointers Slide 1: A pointer references something else, like an index or a node. index_pointer = 2
Two Pointers Slide 2: Using two pointers to compare different elements together saves time and space.
Two Pointers Slide 3: left_index = 1 right_index = 3 One pointer starts at the beginning while the other starts at the end. Both pointers move inward until they meet.
Two Pointers Slide 4: left_index = 1 right_index = 3 One pointer starts at the beginning while the other starts at the end. Both pointers move inward until they meet.
Two Pointers Slide 5: left_index = 2 right_index = 2 One pointer starts at the beginning while the other starts at the end. Both pointers move inward until they meet.
Two Pointers Slide 6: Example question: Given a sorted list of integers, find two numbers that sum up to a target value. Return the indices of the two numbers.
Two Pointers Slide 7: Given a sorted list of integers, find two numbers that sum up to a target value. Return the indices of the two numbers. target = 9
Two Pointers Slide 8: Initialize two pointers pointing at the first and last elements of the array. b = 3 a = 0 target = 9
Two Pointers Slide 9: target = 9 b = 3 a = 0 Calculate the sum of the pointers' values. If values at + is greater than the target, then decrement . Otherwise increment . 2 + 15 >
Two Pointers Slide 10: b = 2 a = 0 2 + 11 > target = 9 Calculate the sum of the pointers' values. If values at + is greater than the target, then decrement . Otherwise increment .
Two Pointers Slide 11: b = 1 a = 0 2 + 7 == target = 9 return [0, 1] Calculate the sum of the pointers' values. If values at + is greater than the target, then decrement . Otherwise increment .

Use ← → arrow keys

Code snippets

# Find two numbers in the list nums that sum up to target.
def two_sum(nums, target):
  a = 0  # Initialize a pointer at beginning of list.
  b = len(nums) - 1  # Initialize another pointer at end of list.

  while a < b:
      current_sum = nums[a] + nums[b]
      
      if current_sum == target:
          return [a, b]  # Return the pair that sums up to target.
      elif current_sum < target:
          a += 1  # We are under target so increase the sum.
      else:
          b -= 1  # We are over target so decrease the sum.

  return None  # We never found a pair that sums up to target.

How to identify

Does the problem involve any of these?

  • Searching for pairs or triplets of elements that satisfy certain conditions
  • Maintaining two pointers to scan a list simultaneously from both ends
  • Maintaining a sliding window or range within the array or list (covered later)
  • Manipulating pointers to nodes in a linked list or tree (covered later)
  • merging or comparing two sorted lists (covered later)

Note

Most two pointer problems can be solved in O(n) time and O(1) space complexity.