DSA Tracker

Blog

Patterns

Two Pointers Pattern: When to Start from Both Ends

Learn when to use two pointers moving inward in DSA interviews, how to avoid boundary bugs, and trace a clean example for placements.

Riya Kushwaha, DSA Tracker team4 min read
On this page

You start two pointers at opposite ends of a sorted array and move them inward when you need to narrow a search space based on a direct comparison of sums or values. If the running sum is too small, advance the left pointer to increase it. If the sum is too large, decrement the right pointer to drop it. This single strategy cuts time complexity down from quadratic bounds to linear bounds.

How to Recognize the Pattern

You should look for this pattern whenever an array is already sorted or when sorting it first does not ruin your time budget. The classic signature is a search for a pair of elements that meet a specific target value. If a problem asks you to find two numbers in an array arr of size n that add up to a target x, the brute force approach checks every pair using nested loops that run in O(n^2) time.

Two pointers turn that search into an O(n) scan. You set left to index 0 and right to index n - 1. You check the sum of arr[left] and arr[right]. Because the array is sorted, moving left strictly increases the sum, and moving right strictly decreases it. There is no guessing. Every single step eliminates an entire row or column of possibilities without visiting them twice.

Moving Inward Versus Same Direction

Opposite-end pointers require sorted data because you rely on monotonicity. When left moves right, values get bigger. When right moves left, values get smaller. You use this inward configuration for problems like Two Sum II, reversing strings in place, or finding container boundaries in Container With Most Water.

Same-direction pointers, like the fast and slow pointer setup in removeDuplicates or linkedListCycle, solve different problems. They track windows or partition data in place without requiring sorted order. If you apply inward pointers to an unsorted array without sorting it first, your logic will fail because the directional guarantee breaks down entirely.

A Worked Example You Can Trace

Take the sorted array arr = [2, 7, 11, 15] and look for a target sum of 9.

Set left = 0 pointing to 2, and right = 3 pointing to 15. Add arr[left] + arr[right], which gives 2 + 15 = 17. Because 17 is greater than 9, decrement right to 2.

Now left = 0 pointing to 2, and right = 2 pointing to 11. Add 2 + 11 = 13. Still larger than 9, so decrement right to 1.

Now left = 0 pointing to 2, and right = 1 pointing to 7. Add 2 + 7 = 9. This matches the target. You return indices 0 and 1. The total operations took three steps instead of checking all six possible pairs.

Common Boundary Traps

The most frequent bug in pointer code is letting left cross right during an invalid state check. Your loop condition must be while (left < right) or while (left <= right) depending on whether a single element can pair with itself. If you write while (left <= right) when pointers must remain distinct, you will test an element against itself when left == right.

Another silent failure happens when updating pointers inside conditional blocks. If you write an infinite loop because neither pointer moves when arr[left] + arr[right] == target in a partitioning problem, your execution will hang. Always ensure that at least one pointer advances on every single iteration of the loop.

Interviewer Expectations by Level

For service-based company coding rounds and initial screening tests, interviewers just want to see that you avoid the O(n^2) nested loop and write clean index management. They check if you remember to handle edge cases like empty arrays or single-element inputs where pointers should not even initialize.

For product-based engineering roles, interviewers expect you to prove why the algorithm works. They will ask you to prove that no valid pairs are skipped when left advances. Master the invariant: every time you move a pointer, you mathematically discard elements that cannot possibly be part of a valid solution. Practice implementing these patterns on DSA Tracker before your next technical round.

Keep going with the step-by-step visualizer and practice problems.

Further reading: Binary search on Wikipedia.

Share

XLinkedInWhatsApp

Frequently asked questions

Do two pointers always require a sorted array?

No. Same-direction pointers for partition or cycle detection work on unsorted data. Inward-moving pointers require sorting to guarantee that moving a pointer predictably changes the sum.

What is the time complexity of a two-pointer approach?

It runs in linear time, written as `O(n)`, because each element is visited at most once by each pointer from opposite ends.

How do I know whether to increment left or decrement right?

Compare your current aggregate value to your target. If the value is too small, advance the left pointer to increase it. If too large, decrement the right pointer.

Practice what you just read

Open one in the editor and submit it. Your code is checked against hidden tests in C++, Java, Python and JavaScript. No account needed.

Keep reading