DEV Community

JAYA SRI J
JAYA SRI J

Posted on

TWO SUM II -167

Two Sum II – Two Pointer Approach (Short Blog)
Problem

Given a sorted array numbers and a target, find two indices such that:

numbers[i] + numbers[j] = target

Return 1-based indices.

Code

class Solution:
    def twoSum(self, numbers, target):
        l = 0
        r = len(numbers) - 1
        while l < r:
            s = numbers[l] + numbers[r]
            if s > target:
                r -= 1
            elif s < target:
                l += 1
            else:
                return [l + 1, r + 1]
Enter fullscreen mode Exit fullscreen mode

Why This Approach?

  1. Array is sorted → we can avoid hash maps Use two pointers instead of nested loops
  2. More efficient → O(n) time, O(1) space

Line-by-Line Idea
l = 0 → start (smallest value)
r = len(numbers)-1 → end (largest value)
while l < r → ensure two different elements
s = numbers[l] + numbers[r] → check current pair

Conditions:
If s > target → decrease sum → r -= 1
If s < target → increase sum → l += 1
If equal → return answer
Key Logic

Because the array is sorted:

Move right pointer left → reduce sum
Move left pointer right → increase sum
Example
numbers = [2, 7, 11, 15], target = 9

Steps:

2 + 15 → too big → move r
2 + 11 → too big → move r
2 + 7 → correct

Output:
[1, 2]

Why It’s Better?

  1. No extra space (no dictionary)
  2. Faster than brute force
  3. Uses sorted property effectively

Top comments (0)