Two Pointers
Medium
Two Sum II - Input Array Is Sorted
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number.
10 min read
Solve on LeetCodeExamples
Input:numbers = [2,7,11,15], target = 9
Output:[1,2]
Explain:
The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].
Input:numbers = [2,3,4], target = 6
Output:[1,3]
Explain:
The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].
Problem Understanding
This is similar to the classic Two Sum, but with two key differences:
- The array is already sorted.
- You must return 1-based indices.
A brute force approach would be to check every pair, which is O(n²). However, the sorted property allows us to use the Two Pointers technique to solve it in linear time O(n).
Algorithm Strategy
- Initialize
leftat the start (index 0) andrightat the end (index n-1). - Calculate
current_sum = numbers[left] + numbers[right]. - If
current_sum == target, we found the pair! Return[left + 1, right + 1]. - If
current_sum < target, we need a larger sum. Since the array is sorted, movingleftto the right increases the sum. - If
current_sum > target, we need a smaller sum. Movingrightto the left decreases the sum.
Interactive Visualization
Step 1 / 1
L
2
07
111
2R
15
3Goal: Find pair adding to 9. Array is sorted. Start pointers at ends.
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run: nums = [2, 7, 11, 15], target = 9
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
