Master the Two Pointer Technique: With 10 Practice Problems
What is the Two Pointer Technique?
The two pointer technique is a pattern where you use two pointers (indices) to traverse a data structure, typically an array or linked list. It's incredibly powerful for solving problems that would otherwise require nested loops (O(n^2)) in O(n) time.
When to Use Two Pointers
Use two pointers when you see:
Types of Two Pointer Approaches
1. Opposite Direction (Start/End)
Both pointers start at opposite ends and move toward each other.
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return []
2. Same Direction (Fast/Slow)
Both pointers start at the same position but move at different speeds.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
3. Sliding Window (Special Case)
A variation where you maintain a window of elements.
def max_sum_subarray(arr, k):
window_sum = sum(arr[:k])
max_sum = window_sum
for i in range(k, len(arr)):
window_sum = window_sum - arr[i-k] + arr[i]
max_sum = max(max_sum, window_sum)
return max_sum
10 Practice Problems
Here are 10 problems to master two pointers (in order of difficulty):
Common Mistakes to Avoid
Time Complexity
Most two pointer solutions run in O(n) time and O(1) space, which is why interviewers love them. They test if you can optimize brute force solutions.
Practice with DSA 100 Days
Our curriculum includes all 10 problems above with AI tutoring to help when you're stuck. [Start practicing today](/signup).