The Two Pointers pattern is one of the most foundational and frequently tested techniques in algorithmic interviews. At its core, it involves using two references (or "pointers") to walk a linear data structure (an array, string or linked list) at the same time. By coordinating the movement of these two pointers, you can often reduce the time complexity of a problem from a brute-force $O(n^2)$ down to a highly efficient $O(n)$, and keep space complexity at a strict $O(1)$. Whether you are checking for palindromes, finding pairs that sum to a specific target, or partitioning an array in-place, mastering this pattern is essential for any software engineer looking to clear top-tier technical rounds.
When to use this pattern
Recognizing when to apply the Two Pointers technique is half the battle. Interviewers rarely tell you to use it directly; instead, they embed signals in the problem statement. Look for these common triggers:
- The input array or string is sorted: If the data is sorted, the relationship between elements at opposite ends is predictable. This allows you to make logical decisions about which pointer to move.
- You need to find a set of elements: Problems asking for pairs, triplets, or subarrays that satisfy a specific mathematical condition (like a target sum) are prime candidates.
- In-place modifications are required: If the interviewer explicitly restricts you to $O(1)$ extra space and asks you to remove duplicates, move zeros, or reverse an array, Two Pointers is almost certainly the expected approach.
- Comparing elements from both ends: Problems involving palindromes or symmetric properties naturally require you to look at the start and end of a sequence simultaneously.
The core idea
The Two Pointers pattern generally manifests in two distinct flavors:
- Opposite Ends (Collision): One pointer starts at the beginning (index
0) and the other at the end (indexn-1). They move towards each other until they meet. This is heavily used in sorted arrays. - Equi-directional (Fast/Slow): Both pointers start at the beginning. One pointer moves faster than the other, or one pointer acts as an "iterator" while the other acts as a "writer". This is common in linked lists and in-place array modifications.
Let's visualize the Opposite Ends approach on a sorted array where we are looking for two numbers that sum to a target:
Because the array is sorted, we know that moving the Left Pointer to the right will increase the sum, and moving the Right Pointer to the left will decrease the sum. This predictable monotonicity is what allows us to discard large portions of the search space in a single step, bypassing the need for nested loops.
Template
While every problem requires specific logic, the skeletal structure of an opposite-ends Two Pointers solution remains remarkably consistent. Memorize this template as your starting point.
def two_pointers_template(arr):
left = 0
right = len(arr) - 1
while left < right:
# Step 1: Evaluate the current state
current_state = evaluate(arr[left], arr[right])
# Step 2: Decide which pointer to move based on the condition
if current_state == "target_met":
return True # Or process the result
elif current_state == "need_larger_value":
left += 1
else:
right -= 1
return FalseWorked examples
Let's apply this pattern to three classic interview problems, ranging from fundamental to advanced. We will break down the approach, trace the logic, and analyze the complexity for each.
Example 1: Two Sum II - Input Array Is Sorted
Problem: Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Return the indices of the two numbers (1-indexed).
Approach:
Since the array is sorted, we can place one pointer at the beginning (left) and one at the end (right). We calculate the sum of the elements at these pointers.
- If
sum == target, we found our pair. - If
sum < target, the current sum is too small. Because the array is sorted, moving therightpointer to the left would only make the sum even smaller. Therefore, we must move theleftpointer to the right to increase the sum. - If
sum > target, the current sum is too large. Moving theleftpointer to the right would make it larger. Therefore, we must move therightpointer to the left to decrease the sum.
Step-by-step trace:
Let numbers = [2, 7, 11, 15] and target = 9.
| Step | Left Index | Right Index | Left Value | Right Value | Sum | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 3 | 2 | 15 | 17 | 17 > 9, move Right left (right--) |
| 2 | 0 | 2 | 2 | 11 | 13 | 13 > 9, move Right left (right--) |
| 3 | 0 | 1 | 2 | 7 | 9 | 9 == 9, Match found! Return [1, 2] |
def twoSum(numbers, target):
left, right = 0, len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum == target:
# +1 because the problem asks for 1-indexed results
return [left + 1, right + 1]
elif current_sum < target:
left += 1
else:
right -= 1
return []Complexity:
- Time Complexity: $O(n)$. We traverse the array at most once. Each element is visited at most once by either the left or right pointer.
- Space Complexity: $O(1)$. We only use two integer variables for the pointers, regardless of the size of the input array.
Example 2: 3Sum
Problem: Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets.
Approach: This is a classic step up from Two Sum. A brute force approach would use three nested loops, resulting in an unacceptable $O(n^3)$ time complexity. We can optimize this by sorting the array first.
Once sorted, we can iterate through the array, treating each element as a fixed target. For a fixed element nums[i], the problem reduces to finding two other elements in the remaining array (nums[i+1] to nums[n-1]) that sum to -nums[i]. This is exactly the Two Sum II problem we just solved!
Handling duplicates is the trickiest part. Because the array is sorted, duplicate numbers will be adjacent. We must skip adjacent duplicates for our fixed pointer i, and also skip adjacent duplicates for our left and right pointers after finding a valid triplet.
def threeSum(nums):
nums.sort()
result = []
n = len(nums)
for i in range(n - 2):
# Skip duplicates for the fixed element
if i > 0 and nums[i] == nums[i - 1]:
continue
left = i + 1
right = n - 1
target = -nums[i]
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
result.append([nums[i], nums[left], nums[right]])
# Skip duplicates for the left pointer
while left < right and nums[left] == nums[left + 1]:
left += 1
# Skip duplicates for the right pointer
while left < right and nums[right] == nums[right - 1]:
right -= 1
# Move both pointers inward after finding a valid triplet
left += 1
right -= 1
elif current_sum < target:
left += 1
else:
right -= 1
return resultComplexity:
- Time Complexity: $O(n^2)$. Sorting takes $O(n \log n)$. The outer loop runs $n$ times, and the inner
whileloop runs at most $n$ times, resulting in $O(n^2)$. The overall time complexity is dominated by $O(n^2)$. - Space Complexity: $O(1)$ or $O(n)$ depending on the sorting algorithm used by the language. We don't use any extra space for our algorithm logic other than pointers.
Example 3: Container With Most Water
Problem: You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the $i^{th}$ line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.
Approach:
This problem introduces a greedy aspect to the Two Pointers pattern. The area of water is determined by: Area = width * min(height_left, height_right).
To maximize the area, we should start with the maximum possible width. We place our left pointer at index 0 and our right pointer at n-1. We calculate the area and update our maximum.
Now, how do we proceed? The width will strictly decrease as we move pointers inward. To have any chance of finding a larger area, we must compensate for the decreasing width by finding a taller height. The height of the container is bottlenecked by the shorter line. Therefore, moving the pointer at the taller line is useless: the area can only decrease because the width decreases and the height cannot exceed the shorter line.
Mathematical Proof for the Greedy Choice:
Suppose height[left] < height[right]. The current area is height[left] * (right - left). If we move the right pointer to right - 1, the new height is min(height[left], height[right - 1]). This new height can be at most height[left]. Thus, the new area is at most height[left] * (right - left - 1), which is strictly less than the original area. Therefore, keeping the shorter line and moving the taller line will never yield a larger area. We must discard the shorter line by moving left to left + 1.
def maxArea(height):
left = 0
right = len(height) - 1
max_area = 0
while left < right:
# Calculate current area
current_width = right - left
current_height = min(height[left], height[right])
current_area = current_width * current_height
# Update max_area if we found a larger one
max_area = max(max_area, current_area)
# Move the pointer pointing to the shorter line
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_areaComplexity:
- Time Complexity: $O(n)$. Both pointers move towards each other and meet in the middle, visiting each element exactly once.
- Space Complexity: $O(1)$. Only a few integer variables are used.
Variations and pitfalls
While the Two Pointers pattern is straightforward in theory, interviewers often introduce twists or candidates fall into common traps. Here is what you need to watch out for:
1. left < right vs left <= right
One of the most frequent bugs candidates write is using the wrong loop condition.
- Use
while left < rightwhen you are comparing two distinct elements (like finding a pair). Ifleft == right, you are looking at the same element, which is usually invalid for pair problems. - Use
while left <= rightwhen you need to process every single element, even the middle one when the array length is odd. This is strictly required in algorithms like Binary Search or when reversing an array where the middle element might need some final processing.
2. Fast and Slow Pointers (Equi-directional)
Instead of starting at opposite ends, both pointers start at index 0. The fast pointer iterates through the array to evaluate elements, while the slow pointer keeps track of the position where the next valid element should be written. This is the standard approach for problems like "Remove Duplicates from Sorted Array" or "Move Zeroes".
3. Two Pointers vs Sliding Window
Candidates often confuse these two patterns. Here is a quick breakdown to help you differentiate them during an interview:
| Feature | Two Pointers | Sliding Window |
|---|---|---|
| Primary Goal | Finding pairs, swapping elements, in-place partitioning. | Finding subarrays or substrings that meet a criteria. |
| Pointer Movement | Independent. Pointers can move towards each other or in the same direction at different speeds. | Coordinated. The window expands (right pointer moves) and shrinks (left pointer moves) to maintain a valid state. |
| Data Relationship | Often requires the data to be sorted (for opposite ends). | Does not require sorted data. Focuses on contiguous sequences. |
4. Integer Overflow
In languages like Java and C++, adding two large integers can result in an overflow. If you are doing arr[left] + arr[right] on an array of large numbers, consider casting to a long before summing, or check constraints carefully. Python handles arbitrarily large integers automatically, so this is less of a concern there.
Practice checklist
Ready to solidify your understanding? The best way to master the Two Pointers pattern is through deliberate practice. Work through these resources on CureBugs to build your muscle memory: