Mastery Points
0
Two Pointer Technique in dsa
Context & Logic
Two Pointer technique uses two indices to traverse a data structure (usually an array or linked list) at the same time to solve problems involving searching or pairs.
Example
// Pair sum in sorted array
function hasPairSum(arr, target) {
let left = 0, right = arr.length - 1;
while (left < right) {
let sum = arr[left] + arr[right];
if (sum === target) return true;
(sum < target) ? left++ : right--;
}
return false;
}Step-by-Step Logic
1
Initialize two pointers (e.g., left at index 0 and right at index n-1).
2
Process the elements at the pointer positions.
3
Move the pointers based on a condition (e.g., increment left if sum is too small).
4
Repeat until the pointers meet or the condition is satisfied.
Complexity Metrics
Time Efficiency
O(n)
Memory Footprint
O(1)