from typing import List, Optional
class TwoPointerArray:
def __init__(self, arr: List[int]):
self.arr = arr
def find_pair_with_sum(self, target: int) -> Optional[tuple]:
left, right = 0, len(self.arr) - 1
while left < right:
current_sum = self.arr[left] + self.arr[right]
if current_sum == target:
return (self.arr[left], self.arr[right])
elif current_sum < target:
left += 1
else:
right -= 1
return None
if __name__ == '__main__':
arr = [1, 3, 5, 7, 9]
target = 12
tp = TwoPointerArray(arr)
result = tp.find_pair_with_sum(target)
if result:
print(f"Pair found {result}")
else:
print("No pair found")left, right = 0, len(self.arr) - 1
initialize two pointers at array ends
loop until pointers meet or cross
current_sum = self.arr[left] + self.arr[right]
calculate sum of values at pointers
if current_sum == target:
check if sum matches target
return (self.arr[left], self.arr[right])
return the pair if found
elif current_sum < target:
if sum too small, move left pointer right to increase sum
if sum too large, move right pointer left to decrease sum