LeetCode ยท #167

Two Sum II Solution

Given a 1-indexed sorted array, find two numbers that add up to target. Return their indices.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Medium

๐Ÿ”—

LeetCode

Problem #167

๐Ÿ—๏ธ

Pattern

Two Pointers โ€” converge on sorted

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.

Example
Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2] // numbers[1] + numbers[2] = 2 + 7 = 9 (1-indexed)
Constraints
โ€ข 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; class Solution { public int[] twoSum(int[] numbers, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < numbers.length; i++) { int comp = target - numbers[i]; if (map.containsKey(comp)) return new int[] { map.get(comp) + 1, i + 1 }; map.put(numbers[i], i); } return new int[] {}; } }
Python โ€” dict (violates O(1) space)
class Solution: def twoSum(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
MetricValue
TimeO(n)
SpaceO(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.
04
Section Four ยท Trace

Visual Walkthrough

Trace through numbers = [2, 7, 11, 15], target = 9:

Converging Two Pointers on sorted array
SORTED ARRAY 2 7 11 15 L=0, R=3: 2 + 15 = 17 > 9 โ†’ too large, R-- L=0, R=2: 2 + 11 = 13 > 9 โ†’ too large, R-- L=0, R=1: 2 + 7 = 9 == target โ†’ return [1, 2] โœ“ Answer: [1, 2] โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Two Pointers
class Solution { public int[] 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 new int[] { left + 1, right + 1 }; // 1-indexed else if (sum < target) left++; // need larger value else right--; // need smaller value } return new int[] {}; // unreachable } }
Python โ€” Two Pointers
class Solution: def twoSum(self, numbers: list[int], target: int) -> list[int]: left, right = 0, len(numbers) - 1 while left < right: total = numbers[left] + numbers[right] if total == target: return [left + 1, right + 1] elif total < target: left += 1 else: right -= 1
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpaceTrade-off
HashMapO(n)O(n)Ignores sorted property; violates O(1) space
Binary Search per elementO(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

CaseInputWhy It Matters
Answer at extremes[1, 5], t=6First check finds it. L=0, R=1 โ†’ 1+5=6.
Negative numbers[-3, 0, 3], t=0Negatives work fine โ€” sorted order still holds.
Duplicates[1, 1, 3], t=2Two 1s sum to 2. L=0, R=2โ†’4>2โ†’R--, R=1โ†’1+1=2 โœ“
Large arrayn = 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.

โ† Back to Two Pointers problems