DEV Community

Jeyaprasad R
Jeyaprasad R

Posted on

Two Sum II - Input Array Is Sorted

In this task, I worked on finding two numbers in a sorted array that add up to a given target value. This problem helped me understand how to efficiently use pointers instead of checking all possible pairs.

What I Did

I created a function twoSum that takes a sorted list of numbers and a target value. The function returns the positions of the two numbers whose sum equals the target.

For example:
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]

This means the numbers at positions 1 and 2 add up to 9.

How I Solved It

To solve this, I used two pointers:

  • l starting from the beginning of the array
  • r starting from the end of the array

Then I checked the sum of the elements at these positions.

At each step:

  • If the sum equals the target, I return their positions
  • If the sum is less than the target, I move the left pointer forward
  • If the sum is greater than the target, I move the right pointer backward

Code

class Solution:
  def twoSum(self, numbers: list[int], target: int) -> list[int]:
    l = 0
    r = len(numbers) - 1

    while l < r:
      summ = numbers[l] + numbers[r]
      if summ == target:
        return [l + 1, r + 1]
      if summ < target:
        l += 1
      else:
        r -= 1
Enter fullscreen mode Exit fullscreen mode

How It Works

Since the array is already sorted, this approach works efficiently by narrowing down the search space from both ends.

Instead of checking every pair, the two-pointer method quickly finds the correct pair in a single pass.

Top comments (0)