Replace O(n²) brute force with intelligent pointer movement. Works on sorted arrays and linked lists.
Target: find two numbers that sum to target. Array is sorted.
Slow = boundary of result. Fast = scanner for unique elements.
left < right, NOT left <= right. When both point to same element, pairing it with itself is invalid.def two_sum_sorted(arr, target): left, right = 0, len(arr) - 1 while left < right: # NOT <= s = arr[left] + arr[right] if s == target: return [left, right] elif s < target: left += 1 # need bigger else: right -= 1 # need smaller return [] # Valid Palindrome def is_palindrome(s): l, r = 0, len(s) - 1 while l < r: if s[l] != s[r]: return False l += 1; r -= 1 return True
# Remove duplicates from sorted array in-place def remove_dupes(arr): if not arr: return 0 slow = 0 for fast in range(1, len(arr)): if arr[fast] != arr[slow]: slow += 1 arr[slow] = arr[fast] return slow + 1 # 3Sum — sort + two pointers for each anchor def three_sum(nums): nums.sort(); res = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i-1]: continue l, r = i+1, len(nums)-1 while l < r: s = nums[i]+nums[l]+nums[r] if s == 0: res.append([nums[i],nums[l],nums[r]]); l+=1; r-=1 elif s < 0: l += 1 else: r -= 1 return res