Description

Two pointer is for when you have a clear case for incrementing the left or right pointer.
?

Runtime

O(n)

Visualization

Two Pointer-1783450848388.webp|439

Pseudocode

left is start index
right is rightmost index
result is any

while left is less then right:
	update result
	if condition(left, right):
		l+=1
	else:
		r-=1

return result

Code

def two_pointer(arr): 
	l, r = 0, len(arr) - 1 
	result = ... # initialize answer 
	while l < r: 
		# look at arr[l] and arr[r], update result if needed 
		if condition(arr[l], arr[r]): 
			l += 1 # left side can't contribute more → discard it
		else: 
			r -= 1 # right side can't contribute more → discard it 
	return result