Day 72: Mastering the Two Pointer Technique in Arrays: A Must-Know DSA Pattern
If you’ve just moved past recursion in your DSA journey, it’s time to unlock one of the most elegant and efficient techniques used in array and string problems: the Two Pointer Technique.
It’s simple in concept, yet incredibly powerful when applied right. Let’s break it down with a classic problem that’s often asked in interviews.
The Problem: Two Sum in a Sorted Array
Given a sorted array of integers nums and a target integer target, return the 1-based indices of the two numbers that add up to the target.
You can assume exactly one solution exists.
Brute Force (O(n²))
A straightforward approach is to use a nested loop and check every pair. It works, but it’s inefficient—especially when input size grows. Interviewers usually look for more optimized thinking.
Optimized with Two Pointers (O(n))
Here’s where the two pointer technique shines. Since the array is sorted, we use two indices:
left starting at the beginning
right starting at the end
At each step:
If nums[left] + nums[right] == target → return the pair
If the sum is too small → move left rightward
If the sum is too big → move right leftward
python
CopyEdit
def twoSum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
curr_sum = nums[left] + nums[right]
if curr_sum == target:
return [left + 1, right + 1]
elif curr_sum < target:
left += 1
else:
right -= 1
Why this works: We’re leveraging the sorted nature of the array to discard irrelevant combinations in constant time. No extra space needed. Clean and efficient.
Where Else Can You Use Two Pointers?
Reversing an array in place
Checking for palindromes
Removing duplicates from a sorted array
Merging two sorted arrays
Trapping rain water (advanced)
When to Reach for This Technique
The data is sorted
You need to find pairs, windows, or symmetrical properties
You want to optimize space and time complexity
Final Thoughts
Two pointers teach you to reason from both ends—a skill that’s algorithmic and deeply strategic. It’s a go-to tool for coding interviews and competitive programming alike.
If you’ve already mastered recursion, two pointers is your next must-conquer concept. It’s intuitive, versatile, and essential in real-world code.
Next step? Try applying this to problems like “Container With Most Water” or “3Sum”. You’ll quickly see just how far this pattern can take you.
Let me know what your favorite two-pointer problem is—or if you’ve seen an interview question where this approach saved the day!
#DSA #CodingInterviews #Arrays #TwoPointers #TechBlog python #ProgrammingTips