Tutorials Data Structures and Algorithms in C#
Two Pointers Pattern
Two Pointers Pattern: free step-by-step lesson with examples, common mistakes, and interview tips — part of Data Structures and Algorithms in C# on Toolliyo Academy.
On this page
Data Structures and Algorithms in C# · Lesson 17 of 120
Two Pointers Pattern
Foundations & Arrays → Lists, Hash, Trees → Graphs & DP → Advanced & Projects
Foundations & Arrays · 1 — Basics · ~6 min · Arrays and Strings
What is this?
Two pointers move indices through a collection to avoid O(n²) nested scans — common on sorted arrays and palindromes.
Why should you care?
Many Easy/Medium array problems collapse once you see left/right pointers.
See it live — copy this example
Run snippets in a .NET console app, LINQPad, or https://dotnetfiddle.net. Write Big O above every solution.
bool TwoSumSorted(int[] a, int target) {
int L = 0, R = a.Length - 1;
while (L < R) {
int sum = a[L] + a[R];
if (sum == target) return true;
if (sum < target) L++;
else R--;
}
return false;
}
What happened?
- Array must be sorted for this variant.
- Move the pointer that can fix the sum.
- Each step progresses — O(n).
Practice next
- Test with {1,2,3,9}, target 5.
- Trace L/R on paper.
- Write a palindrome check with two pointers.
- Count pairs under a limit.
- Remove duplicates in-place with slow/fast pointers.
Remember
Sorted → two pointers shine. Each step must progress. Know Dictionary alternative.
Sorted pair search
Find if two numbers make a budget.
Outcome: O(n) after sort or O(n) with HashSet.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!