1. Introduction to Two Pointers
Two pointers technique reduces O(n²) search to O(n). Below are 20 essential questions with full implementations in C++, Java, Python, and JavaScript.
2. Core Two Pointers Questions
Q1. Two Sum II — Sorted Array
cppvector<int> twoSum(vector<int>& numbers, int target) { int left = 0, right = numbers.size() - 1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return {left + 1, right + 1}; else if (sum < target) left++; else right--; } return {}; }
javapublic int[] twoSum(int[] numbers, int target) { int left = 0, right = numbers.length - 1; while (left < right) { int sum = numbers[left] + numbers[right]; if (sum == target) return new int[]{left + 1, right + 1}; else if (sum < target) left++; else right--; } return new int[]{}; }
pythondef twoSum(numbers: list, target: int) -> list: left, right = 0, len(numbers) - 1 while left < right: total = numbers[left] + numbers[right] if total == target: return [left + 1, right + 1] elif total < target: left += 1 else: right -= 1 return []
javascriptfunction twoSum(numbers, target) { let left = 0, right = numbers.length - 1; while (left < right) { let total = numbers[left] + numbers[right]; if (total === target) return [left + 1, right + 1]; else if (total < target) left++; else right--; } return []; }
Time Complexity: O(n) | Space Complexity: O(1)
3. Summary Table
| Problem | Technique | Time | Space |
|---|---|---|---|
| Two Sum II | Opposite-End Pointers | O(n) | O(1) |
Practice all two pointer problems on DSAMaster's practice platform.
