What is the two-pointer technique?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Data Structures & Algorithms basics — a prerequisite for any developer role.

Answer

The two-pointer technique uses two pointers (indices) that move through an array or string, often reducing O(n²) brute force to O(n). Patterns: (1) Opposite ends (converging): one pointer starts at left, one at right, move toward each other based on a condition. Examples: Two Sum in sorted array (if sum too large, move right pointer left; too small, move left pointer right), Valid Palindrome, Container With Most Water, 3Sum; (2) Same direction (fast/slow or window): both start at left, move at different speeds. Examples: Remove Duplicates from Sorted Array (slow pointer writes, fast reads), Linked List cycle detection (Floyd's), finding middle of linked list; (3) Sliding window: both pointers define a window that expands/contracts — Longest Substring Without Repeating Characters, Minimum Window Substring. Prerequisites: often requires sorted array or specific constraints. Examples in detail: Two Sum (sorted): while(l<r){sum=arr[l]+arr[r]; if(sum==target)return[l,r]; sum<target?l++:r--;}. Time: O(n). Two pointers is a fundamental pattern for array/string problems — recognizing when it applies is key to efficient solutions.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real Data Structures & Algorithms project.