DSA — Two Pointers
What is Two Pointers?
Using two pointers to traverse a data structure, usually from different ends.
Two Sum (Sorted Array)
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 [-1, -1]
Remove Duplicates
def remove_duplicates(arr):
if not arr:
return 0
slow = 0
for fast in range(1, len(arr)):
if arr[fast] != arr[slow]:
slow += 1
arr[slow] = arr[fast]
return slow + 1
Merge Sorted Arrays
def merge_sorted(arr1, arr2):
result = []
i = j = 0
while i < len(arr1) and j < len(arr2):
if arr1[i] <= arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
result.extend(arr1[i:])
result.extend(arr2[j:])
return result
Patterns
| Pattern | Description |
|---|---|
| Opposite ends | Start from both ends |
| Same direction | Slow and fast pointers |
| Merging | Merge two sorted sequences |
Mini Practice
- Two sum in sorted array
- Remove duplicates
- Merge sorted arrays
- Check if palindrome
Up Next
Continue with Bit Manipulation — bitwise operations.
Related Topics
Frequently Asked Questions about Two Pointers
What is Two Pointers in DSA?
Two Pointers is a fundamental concept in DSA. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Two Pointers?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Two Pointers.
Why is Two Pointers important in DSA?
Two Pointers is essential for DSA development. Understanding this concept will help you write better code and solve real-world problems more effectively.