NeetCode 150 · Two Pointers

Two Pointers Problems

Two pointers moving toward each other (or in the same direction) eliminate the O(n²) brute force for sorted arrays and string problems.

Problems: 5
Easy: 1
Medium: 3
Hard: 1
Learning approach: Read the problem. Try the test cases yourself first. Click Hint if stuck — it guides without spoiling. Use Show Solution only after a genuine attempt. Then hit Let's Code to run your solution live.
01 Easy StringTwo Pointers
Given string s, return True if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Test Cases
isPalindrome('A man, a plan, a canal: Panama') → True isPalindrome('race a car') → False isPalindrome(' ') → True
isalnum()lower()two pointers
Use two pointers from both ends. Skip non-alphanumeric characters and compare the rest case-insensitively.
Python Solution
def isPalindrome(s): left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True
Key idea: Two pointers from both ends. Skip non-alphanumeric characters. Compare the alphanumeric chars case-insensitively. If all match, it's a palindrome.
Time: O(n).
Space: O(1).
02 Medium ArrayTwo PointersBinary Search
Given a 1-indexed sorted array numbers and a target, return the indices of the two numbers (1-indexed) that add up to target. Exactly one solution exists.
Test Cases
twoSum([2,7,11,15], 9) → [1, 2] twoSum([2,3,4], 6) → [1, 3] twoSum([-1,0], -1) → [1, 2]
two pointerssorted array propertyO(n)
The array is sorted. Start with pointers at both ends. If the sum is too big, move the right pointer left; if too small, move the left pointer right.
Python Solution
def twoSum(numbers, target): left, right = 0, len(numbers) - 1 while left < right: s = numbers[left] + numbers[right] if s == target: return [left + 1, right + 1] elif s < target: left += 1 else: right -= 1
Key idea: The sorted property means we can move pointers deterministically. Too small → move left pointer right (increase sum). Too large → move right pointer left (decrease sum).
Time: O(n).
Space: O(1).
03 Medium ArrayTwo PointersSorting
Given integer array nums, return all triplets [nums[i], nums[j], nums[k]] such that they sum to zero and i != j != k. Answer must not contain duplicate triplets.
Test Cases
threeSum([-1,0,1,2,-1,-4]) → [[-1,-1,2],[-1,0,1]] threeSum([0,1,1]) → [] threeSum([0,0,0]) → [[0,0,0]]
sorttwo pointersskip duplicates
Sort first, then fix the first element and use two pointers for the remaining pair. Skip duplicates at each level to avoid repeated triplets.
Python Solution
def threeSum(nums): nums.sort() result = [] for i, a in enumerate(nums): if i > 0 and nums[i] == nums[i - 1]: continue # skip duplicate first elements left, right = i + 1, len(nums) - 1 while left < right: s = a + nums[left] + nums[right] if s == 0: result.append([a, nums[left], nums[right]]) left += 1 while left < right and nums[left] == nums[left - 1]: left += 1 # skip duplicate second elements elif s < 0: left += 1 else: right -= 1 return result
Key idea: Sort the array. Fix the first element a with a loop; find the other two with two pointers. Skip duplicates at both levels to avoid repeated triplets.
Time: O(n²) — O(n log n) sort + O(n²) two-pointer scan.
Space: O(1) extra.
04 Medium ArrayTwo PointersGreedy
Given integer array height of length n representing line heights, find two lines that together with the x-axis forms a container holding the most water.
Test Cases
maxArea([1,8,6,2,5,4,8,3,7]) → 49 maxArea([1,1]) → 1
two pointersarea formulagreedy shrink short side
Area = min(height[l], height[r]) × (r - l). Which pointer should you move to potentially find a larger area?
Python Solution
def maxArea(height): left, right = 0, len(height) - 1 best = 0 while left < right: water = min(height[left], height[right]) * (right - left) best = max(best, water) # Move the shorter side — the width can only decrease, # so we need a taller side to improve if height[left] <= height[right]: left += 1 else: right -= 1 return best
Key idea: Always move the pointer at the shorter line. Moving the taller one can only maintain or reduce the area. Moving the shorter one might find a taller line that compensates for the reduced width.
Time: O(n).
Space: O(1).
05 Hard ArrayTwo PointersStack
Given n non-negative integers representing an elevation map, compute how much water it can trap after raining.
Test Cases
trap([0,1,0,2,1,0,1,3,2,1,2,1]) → 6 trap([4,2,0,3,2,5]) → 9
two pointerstrack left_max/right_maxO(n) O(1)
At each index, water = min(max_left, max_right) - height[i]. Use two pointers and update the smaller side's max to avoid a second pass.
Python Solution
def trap(height): if not height: return 0 left, right = 0, len(height) - 1 left_max = right_max = water = 0 while left < right: if height[left] <= height[right]: if height[left] >= left_max: left_max = height[left] else: water += left_max - height[left] left += 1 else: if height[right] >= right_max: right_max = height[right] else: water += right_max - height[right] right -= 1 return water
Key idea: Water at any point = min(left_max, right_max) - height. Two pointers let us process the side with the smaller max — we know the bottleneck is on that side, so the water contribution is certain.
Time: O(n).
Space: O(1).
← Prev Category Next Category →