Beginner LevelData Structures & Algorithms
What is the Two-Pointer Technique?
ā Interview Prompt: Explain the Two-Pointer pattern, when to apply it, and solve the classic Two-Sum II (sorted array) and Palindrome problems.
The Two-Pointer Technique uses two indices that typically start at opposite ends (or same end) of an array and converge, reducing nested loop $O(N^2)$ problems to $O(N)$.
When to Apply:
ā¢
Array/string is sorted or the problem involves comparing elements from both ends.
ā¢
Finding pairs that sum to a target.
ā¢
Checking palindromes, removing duplicates in-place.
ā¢
Sliding window variants (fast + slow pointers).
Code Implementation Example
typescript
// Two-Sum II ā sorted array, O(N) time, O(1) space
function twoSumSorted(numbers: number[], target: number): [number, number] {
let left = 0, right = numbers.length - 1;
while (left < right) {
const sum = numbers[left] + numbers[right];
if (sum === target) return [left + 1, right + 1]; // 1-indexed
if (sum < target) left++;
else right--;
}
return [-1, -1];
}
// Palindrome check ā O(N) time
function isPalindrome(s: string): boolean {
let l = 0, r = s.length - 1;
while (l < r) {
if (s[l] !== s[r]) return false;
l++; r--;
}
return true;
}š”Two-pointer solving Two-Sum II and palindrome check in O(N).
šÆ Interview Key Takeaway
Two-pointers reduce O(N²) pair-search problems to O(N) by exploiting sorted order or symmetry. Master this before interviews.
#DSA#Two Pointers#Patterns#Arrays#Beginner
Back to all Data Structures & Algorithms Questionsā