Data Structures and Algorithms • C# examples
Two-Pointer Techniques
Use coordinated indices to reduce repeated work in sorted arrays and sequence problems.
Concept
Two pointers move through a sequence according to a condition. On a sorted array, pointers at opposite ends can find a pair with a target sum; on a linked list, slow and fast pointers can detect cycles. The proof depends on why a pointer movement safely discards candidates.
How to approach it
Write down what each pointer represents and prove that every move removes only impossible solutions.
Complexity
Many two-pointer scans are O(n) time and O(1) extra space.
C# example
int left = 0, right = values.Length - 1;
while (left < right)
{
long sum = (long) values[left] + values[right];
if (sum == target) break;
if (sum < target) left++;
else right--;
}
Expected result or behavior
For sorted input, each iteration discards at least one candidate pair.
Practice exercise
Adapt the method to return the pair of values and prove why each movement is safe.
Key takeaway: Pointer movement needs a correctness argument, not just a loop that appears to work.