Using Two Pointers
def twoPointers(array: list[int], target: int) -> bool:
left = 0
right = len(array) - 1
while left < right:
answer = array[left] + array[right]
if answer == target:
return True
elif answer > target:
right -= 1
elif answer < target:
left += 1
return False Code Explanation
Initialize Pointers:
left = 0
right = len(array) - 1leftis initialized to the first index of the array (0).rightis initialized to the last index of the array (len(array) - 1).
Two-Pointer Approach:
The loop continues as long as
leftis less thanright. This condition ensures that the two pointers do not cross and that distinct elements are considered.
Check the Sum (answer):
Calculate the sum (
answer) of the elements at theleftandrightpointers.If
answerequals thetarget, the function returnsTrue, indicating that a pair with the desired sum has been found.
Adjust Pointers Based on the Comparison:
If
answeris greater thantarget, decrement therightpointer (right -= 1). This moves therightpointer to a smaller element, reducing the sum.If
answeris less thantarget, increment theleftpointer (left += 1). This moves theleftpointer to a larger element, increasing the sum.
How It Works: The two-pointer method works by leveraging the sorted nature of the array. By adjusting the pointers (left, right) based on the current sum (answer), it efficiently narrows down the search space for finding the desired pair.
This technique ensures that all potential pairs are considered without redundancy.
Connected Readings
When to use a Two Pointer Approach by Geeksforgeeks (Link)
Last updated