The two pointer technique uses two pointers to traverse a data structure (usually an array or linked list) from different directions or at different speeds. This approach is highly efficient for problems involving sorted arrays, palindromes, and finding pairs that satisfy certain conditions.
# Python - Two Sum in sorted array
def two_sum(arr, target):
"""Find two numbers that sum to target"""
left, right = 0, len(arr) - 1
while left < right:
current_sum = arr[left] + arr[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return []
# Example: arr = [2,7,11,15], target = 9
# Output: [0, 1]
// C++ - Two Sum in sorted array
std::vector<int> twoSum(std::vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
return {left, right};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {};
}
// C# - Two Sum in sorted array
int[] TwoSum(int[] arr, int target) {
int left = 0, right = arr.Length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
return new int[] { left, right };
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[] { };
}
// Java - Two Sum in sorted array
int[] twoSum(int[] arr, int target) {
int left = 0, right = arr.length - 1;
while (left < right) {
int sum = arr[left] + arr[right];
if (sum == target) {
return new int[] { left, right };
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[] { };
}