The example problem
Given a list of numbers sorted from small to large and a target, find the two numbers that add up to the target and return their positions (LeetCode counts from 1).
Input: [1, 3, 4, 6, 8, 11, 13, 15], target = 10 Output: [3, 4] (positions of 4 and 6, counting from 1)
Picture it
Picture a row of lockers numbered in increasing order, with one friend at each end. They add their two locker numbers. Too big? The friend on the right steps left to a smaller locker. Too small? The friend on the left steps right to a bigger one. Because the row is sorted, each step safely rules out a locker, and they meet the answer without trying every pair.
The key idea
Sorted input lets two pointers squeeze inward: sum too big → move right pointer left, too small → move left pointer right. O(n).
Python
def two_sum(nums, target):
l, r = 0, len(nums) - 1
while l < r:
s = nums[l] + nums[r]
if s == target:
return [l + 1, r + 1] # 1-based
if s < target:
l += 1
else:
r -= 1
return []Practise two pointers
- LeetCode 5Longest Palindromic SubstringA mirror sliding along the letters
- LeetCode 11Container With Most WaterTwo fence posts holding water
- LeetCode 153SumThree lockers that cancel out
- LeetCode 26Remove Duplicates from Sorted ArrayA reader and a writer on a sorted shelf
- LeetCode 42Trapping Rain WaterRain pooling between buildings
- LeetCode 75Sort Colors (Dutch flag)Sorting red, white and blue marbles
- LeetCode 88Merge Sorted ArrayFilling a parking row from the back
- LeetCode 125Valid PalindromeReading a sign from both ends
- LeetCode 189Rotate ArrayTurning a carousel with three flips
- LeetCode 283Move ZeroesPushing empty slots to the end of a shelf
- LeetCode 344Reverse StringTwo friends swapping letter cards
NeetCode 150 problems that use it
Two Pointers ·
- LeetCode 125 · EasyValid PalindromeReading a sign from both ends
- LeetCode 167 · MediumTwo Sum IITwo friends, one row of lockers
- LeetCode 15 · Medium3SumThree lockers that cancel out
- LeetCode 11 · MediumContainer With Most WaterTwo fence posts holding water
- LeetCode 42 · HardTrapping Rain WaterRain pooling between buildings