Coding Pattern:
Two Pointers
This pattern has an earnable cheat sheet.
Pattern concept
Step 1 of 11
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
- Sum of Three: Find triplets that sum up to a target.
- Best Time to Buy and Sell Stock: Find a pair of elements with max profit.
- Maintaining two pointers to scan a list simultaneously from both ends
- Valid Palindrome: Check whether a string is a valid palindrome.
- Valid Palindrome II: Check whether a string is almost a valid palindrome.
- Trapping Rain Water: Scan the list to calculate the amount of rainwater that can be trapped.
- 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.