Two Sum II Visualization & Animation
Finds two indices in a sorted array that sum to a target using opposite-end two pointers; O(n) time, O(1) space.
## What is it?
Given a sorted array of integers and a target sum, find the two indices whose values add up to the target. The classic two-pointer problem on a sorted array (LeetCode 167).
## How it works
- Place `left = 0` (beginning), `right = n-1` (end)
- If `arr[left] + arr[right] == target` → return `[left+1, right+1]` (1-indexed)
- If sum < target → move `left++` (need a larger value)
- If sum > target → move `right--` (need a smaller value)
- Repeat until found
## When to use
- Two sum on a sorted array
- Any "find a pair summing to target" in sorted data
- Foundation for Three Sum (sort first, then apply two pointers)
## Key Points
- Works only on sorted arrays — sort first if needed (but then it costs O(n log n))
- O(n) time, O(1) space — optimal for sorted input
- Guaranteed to find a solution by the problem constraints (exactly one solution)
Category: algorithms
Difficulty: intermediate
Time Complexity: O(n)
Space Complexity: O(1)
View Two Sum II Visualization