Using Two Pointers
Code Explanation
Initialize Pointers:
left
is initialized to the first index of the array (0).right
is initialized to the last index of the array (len(array) - 1
).
Two-Pointer Approach:
The loop continues as long as
left
is 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 theleft
andright
pointers.If
answer
equals thetarget
, the function returnsTrue
, indicating that a pair with the desired sum has been found.
Adjust Pointers Based on the Comparison:
If
answer
is greater thantarget
, decrement theright
pointer (right -= 1
). This moves theright
pointer to a smaller element, reducing the sum.If
answer
is less thantarget
, increment theleft
pointer (left += 1
). This moves theleft
pointer 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