Welcome to the Patterns section of the DSA course. You already know the building blocks: arrays, sorting, hashing, trees. Now we learn the tricks interviewers actually test. The first one is the easiest and the most asked: the two pointers technique.
Learn it once and you can solve dozens of problems: pair sum, palindrome check, 3Sum, container with most water, remove duplicates and more.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stackcoming soon
- 8Heap / Top-Kcoming soon
- 9Tree Patternscoming soon
- 10Grid BFS & Topological Sortcoming soon
- 11Backtrackingcoming soon
- 12DP Patternscoming soon
The shopping story (remember this, forget the code)
You and a friend have exactly ₹100 and want to buy two items from a shelf where prices are arranged from cheapest to costliest. You stand at the cheapest end. Your friend stands at the costliest end.
- Add the two prices. Too costly? Your friend steps to a cheaper item.
- Too cheap? You step to a costlier item.
- Exactly ₹100? Done.
Nobody ever walks backwards, so you check each item at most once. That's the whole technique. Try it:
🛒 Spend the exact budget: two friends, one sorted shelf
Step 1: ₹10 + ₹95 = ₹105. Too costly: the RIGHT friend moves to a cheaper item.
Two pointers checked 1 pair. Checking every pair (brute force) would take up to 28. For 1 lakh items that's 1 lakh steps vs about 5 billion.
Why it works (the one idea)
Because the shelf is sorted, every move throws away options safely. If ₹10 + ₹95 is too costly, then ₹95 with anything is too costly (everything else is pricier than ₹10). So we drop ₹95 for good. One step removes a whole row of pairs. That's how n² pairs become n steps.
🔍 Use two pointers when you see
- ✓The array is sorted (or you're allowed to sort it)
- ✓You need a pair or triplet with a target sum
- ✓Compare from both ends: palindrome, reverse
- ✓Do it “in place” with O(1) extra space
🚫 Don't use it when
- ✗The array is unsorted and you must keep the original order (use a hash map)
- ✗The question asks about a contiguous subarray (use sliding window)
- ✗You need all combinations (use backtracking)
The template (only 8 lines to remember)
left, right = 0, len(arr) - 1
while left < right:
if found(arr[left], arr[right]): return answer
elif too_small: left += 1 # need bigger → left walks right
else: right -= 1 # need smaller → right walks left
return not_found⚡ Memory tricks
- 1
“Sorted + pair → two pointers”
If you see both words in a question, try this first.
- 2
“Too small? Left walks. Too big? Right walks.”
The left end holds the small numbers, the right end holds the big ones.
- 3
“Never walk back”
Each pointer only moves inward, so the total work is one pass: O(n).
- 4
“Stop when the friends meet”
Loop while left < right. Meeting means every pair is checked.
Code: pair sum and palindrome (Python, Java, C++)
Same pattern, two different problems. Every sample below was run, and the outputs in the comments are real.
def pair_with_sum(nums, target):
"""nums is SORTED. Return the two numbers that add up to target."""
left, right = 0, len(nums) - 1
while left < right:
total = nums[left] + nums[right]
if total == target:
return nums[left], nums[right]
if total < target:
left += 1 # too small: move the small end up
else:
right -= 1 # too big: move the big end down
return None
def is_palindrome(s):
"""Ignore spaces and punctuation; compare from both ends."""
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
elif not s[right].isalnum():
right -= 1
elif s[left].lower() != s[right].lower():
return False
else:
left += 1
right -= 1
return True
print(pair_with_sum([1, 3, 4, 6, 8, 11], 10)) # (4, 6)
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(is_palindrome("race a car")) # FalseOne pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Two Sum II (sorted input) | Left and right ends, move by sum | Medium |
| Valid Palindrome | Compare ends, skip non-letters | Easy |
| Reverse String / Reverse Vowels | Swap ends, walk inward | Easy |
| Remove Duplicates from Sorted Array | Slow writer + fast reader pointer | Easy |
| Container With Most Water | Move the shorter wall inward | Medium |
| 3Sum | Fix one number, two pointers on the rest | Medium |
| Trapping Rain Water | Two pointers with left-max and right-max | Hard |
🎯 Spot the pattern: is it two pointers?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Given a sorted array, find two numbers that add up to a target.
2. Check if a sentence reads the same forwards and backwards (ignore spaces).
3. Find the longest substring without repeating characters.
4. Move all zeros in an array to the end, in place, keeping order of the rest.
5. Count how many times each word appears in a paragraph.
🧠 PATH memory card
Remember two pointers for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
Two friends with ₹100 at the two ends of a sorted shelf. Too costly: the right friend steps to a cheaper item. Too cheap: the left friend steps to a costlier one.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Sorted shelf, two friends: too small, left walks; too big, right walks”
- Sorted shelf→Two pointers needs sorted data for pair sums
- Two friends→left = 0, right = n − 1
- Too small, left walks→sum < target → left += 1
- Too big, right walks→sum > target → right −= 1
- Friends meet→while left < right: stop when they meet
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Find a pair adding to 10 in[1, 3, 4, 6, 8, 11]: 1+11=12 (big → R) · 1+8=9 (small → L) · 3+8=11 (big → R) · 3+6=9 (small → L) · 4+6=10 ✓. Five checks instead of fifteen. Write it once on paper. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 7 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Forgetting to sort. On unsorted data the “move left / move right” rule gives wrong answers with no error.
- Using
left <= right. For pairs you need two different items, so useleft < right. - Moving both pointers on a miss. Move only the one the rule says, or you can skip the answer.
Where to go next
Two pointers usually start at opposite ends. What if both pointers start on the left and move the same way, keeping a stretch of the array between them? That's the next pattern, and it solves every “longest substring” question: the sliding window technique.
Key takeaways
- ✓Two pointers = one index at each end, moving inward by a simple rule.
- ✓Signals: sorted, pair or triplet, target sum, from both ends, in place.
- ✓Too small → left walks right. Too big → right walks left. Stop when they meet.
- ✓O(n) time and O(1) space instead of O(n²) for checking every pair.
- ✓Unsorted and order matters? Use a hash map instead.
Frequently asked questions
What is the two pointers technique in simple words?
You keep two positions (pointers) in an array or string and move them based on a simple rule, usually one from each end walking towards the middle. Each step throws away options that can't be the answer, so you finish in one pass, O(n), instead of checking every pair, O(n²).
When should I use two pointers?
When the input is sorted (or you can sort it) and you need a pair or triplet with a target sum, or when you compare items from both ends, like checking a palindrome or reversing in place. The words 'sorted', 'pair', 'in place' and 'from both ends' are the signals.
Does two pointers work on an unsorted array?
For pair-sum problems, no: the rule 'too small, move left; too big, move right' only works because the array is sorted. On unsorted data, either sort first (O(n log n)) or use a hash map (O(n)). Palindrome and reverse problems don't need sorting.
What is the time complexity of the two pointers technique?
Usually O(n) time and O(1) extra space, because each pointer moves at most n times and you store nothing extra. If you have to sort first, the total becomes O(n log n). 3Sum is O(n²): one loop plus a two-pointer walk inside it.
What is the difference between two pointers and sliding window?
Both use two indexes. In two pointers they usually start at opposite ends and move towards each other. In a sliding window both start at the left and move in the same direction, keeping a contiguous 'window' between them. Sliding window is the next lesson.
🧠 Quick check: two pointers
1. Sorted array, pair-sum problem. The current sum is too SMALL. What do you do?
2. Which problem is NOT a good fit for two pointers?
3. What is the usual time complexity of two pointers on a sorted array?
4. When do the two pointers stop?
Checking your access…