DEV Community

JAYA SRI J
JAYA SRI J

Posted on • Edited 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 is 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 is ensure two different elements
s = numbers[l] + numbers[r] it check current pair

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

Because the array is sorted:

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

Steps:

2 + 15 istoo big that move r
2 + 11 is too big that move r
2 + 7 is 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)