Please see github.com/anusha-murali for all of my repositories.
The “two pointer” solution approach is an algorithmic technique that uses two pointers (indices) to traverse a data structure like an array or linked list, often moving them in different directions, to efficiently solve problems by comparing elements at those positions and making decisions based on those comparisons, typically achieving a time complexity of $O(n)$ where $n$ is the size of the data structure; it’s particularly useful for problems involving sorted arrays or finding pairs that meet certain conditions.
Iterate through the array with one pointer at the beginning and one at the end, adjusting pointers based on whether the current sum is too large or too small compared to the target.
Use two pointers, one to iterate through the array and another to mark the position where the next unique element should be placed.
Maintain a “sliding window” using two pointers to track the start and end of the window, adjusting the window size as needed.
Use two pointers, one at the beginning and one at the end of the string, to compare characters and move inwards.
def two_sum(nums, target):
left, right = 0, len(nums) - 1
while left < right:
current_sum = nums[left] + nums[right]
if current_sum == target:
return [left, right]
elif current_sum < target:
left += 1
else:
right -= 1
return []