LC 167 ยท Two Sum II โ Input Array Is Sorted โ Solution & Explanation | DSA Guide
Two approaches to LeetCode Two Sum II โ HashMap O(n) and optimal converging two pointers O(n) with O(1) space. Java and Python solutions with visual walkthrough.
LeetCode ยท #167
Two Sum II Solution
Given a 1-indexed sorted array, find two numbers that add up to target. Return their indices.
Given a 1-indexed array of integers numbers sorted in non-decreasing order, find two numbers that add up to a specific target. Return their indices as [index1, index2] where 1 โค index1 < index2. You must use only constant extra space.
โข 2 โค numbers.length โค 3 ร 10โดโข -1000 โค numbers[i] โค 1000โข numbers is sorted in non-decreasing orderโข Exactly one solution existsโข Must use O(1) extra space
02
Section Two ยท Approach 1
Brute Force โ HashMap O(n)
Use the same HashMap approach as LC 1 (Two Sum). This works but ignores the sorted property and uses O(n) space โ violating the constant-space constraint.
Problem: A HashMap uses O(n) space. Since the array is sorted, two converging pointers can find the pair in O(n) time with O(1) space โ no map needed.
Java โ HashMap (violates O(1) space)
import java.util.HashMap;
classSolution {
publicint[] twoSum(int[] numbers, int target) {
HashMap<Integer, Integer> map = newHashMap<>();
for (int i = 0; i < numbers.length; i++) {
int comp = target - numbers[i];
if (map.containsKey(comp))
return newint[] { map.get(comp) + 1, i + 1 };
map.put(numbers[i], i);
}
return newint[] {};
}
}
Python โ dict (violates O(1) space)
classSolution:
deftwoSum(self, numbers: list[int], target: int) -> list[int]:
seen = {}
for i, num in enumerate(numbers):
if target - num in seen:
return [seen[target - num] + 1, i + 1]
seen[num] = i
Metric
Value
Time
O(n)
Space
O(n) โ violates constraint
03
Section Three ยท Approach 2
Two Pointers โ O(n) time, O(1) space
Place left at the start and right at the end. Compute their sum. If it equals target, done. If too small, move left right (increase sum). If too large, move right left (decrease sum).
๐ก Mental model: Imagine a thermostat dial with two knobs. The left knob only turns right (warmer), the right knob only turns left (cooler). You're trying to hit an exact temperature. Too cold? Move the left knob. Too hot? Move the right. Since the dial is sorted, you converge guaranteed.
Algorithm
Step 1: Set left = 0, right = n - 1.
Step 2: Compute sum = numbers[left] + numbers[right].
Step 3: If sum == target โ return [left+1, right+1] (1-indexed).
Step 4: If sum < target โ left++ (need a larger value).
Step 5: If sum > target โ right-- (need a smaller value).
๐ฏ Why it's correct:
The sorted order guarantees monotonic behavior.
Moving left right can only increase the sum; moving right left can only decrease it.
Since exactly one solution exists, the pointers must meet it.
No valid pair is skipped because every decision eliminates only impossible candidates.
classSolution {
publicint[] twoSum(int[] numbers, int target) {
int left = 0, right = numbers.length - 1;
while (left < right) {
int sum = numbers[left] + numbers[right];
if (sum == target)
return newint[] { left + 1, right + 1 }; // 1-indexedelse if (sum < target)
left++; // need larger valueelse
right--; // need smaller value
}
return newint[] {}; // unreachable
}
}
Python โ Two Pointers
classSolution:
deftwoSum(self, numbers: list[int], target: int) -> list[int]:
left, right = 0, len(numbers) - 1while left < right:
total = numbers[left] + numbers[right]
if total == target:
return [left + 1, right + 1]
elif total < target:
left += 1else:
right -= 1
06
Section Six ยท Analysis
Complexity Analysis
Approach
Time
Space
Trade-off
HashMap
O(n)
O(n)
Ignores sorted property; violates O(1) space
Binary Search per element
O(n log n)
O(1)
Slower; binary search for each complement
Two Pointers โ optimal
O(n)
O(1)
Exploits sorted order. One pass, no extra memory.
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
Case
Input
Why It Matters
Answer at extremes
[1, 5], t=6
First check finds it. L=0, R=1 โ 1+5=6.
Negative numbers
[-3, 0, 3], t=0
Negatives work fine โ sorted order still holds.
Duplicates
[1, 1, 3], t=2
Two 1s sum to 2. L=0, R=2โ4>2โR--, R=1โ1+1=2 โ
Large array
n = 3ร10โด
O(n) handles it easily. At most n iterations.
โ Common Mistake: Returning 0-indexed instead of 1-indexed results. The problem specifies 1-indexed โ remember to add 1 to both indices before returning.