Data Structures & Algorithms Two Pointers
💡
Exercise 36

Two Sum II 15 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

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

Since the array is sorted, we can use two pointers instead of a hash map. This gives us O(1) space instead of O(n).

numbers = [2, 7, 11, 15], target = 9 # Output: [1, 2] (1-indexed) # numbers[0] + numbers[1] = 2 + 7 = 9

Why two pointers work on sorted arrays: if the sum is too small, moving left pointer right increases it. If too large, moving right pointer left decreases it.

📋 Instructions
Implement `two_sum_ii(numbers, target)` using two pointers. Return 1-indexed results. Test with `numbers = [2, 7, 11, 15]`, `target = 9`. Print the result.
Left pointer at index 0, right at end. Sum = numbers[left] + numbers[right]. If sum == target, return [left+1, right+1]. If sum < target, left++. If sum > target, right--.
🧪 Test Cases
Input
two_sum_ii([2, 7, 11, 15], 9)
Expected
[1, 2]
Test case 1
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.