DEV Community

Ashiq Omar
Ashiq Omar

Posted on

Two Sum (Sorted Array)

In this task, I worked on finding two numbers in a sorted array that add up to a given target.
The goal is to return their 1-based indices.

What I Did
I implemented a function twoSum that takes:
a sorted array numbers
a target value
and returns the indices of the two numbers whose sum equals the target.

Example:
Input: numbers = [2, 7, 11, 15], target = 9

Output: [1, 2]

Explanation:
2 + 7 = 9 → indices are 1 and 2
How I Solved It

Instead of brute force (O(n²)), I used the Two Pointer Technique.

Core Idea:

Since the array is sorted:

  • If sum is too small → move left pointer forward
  • If sum is too large → move right pointer backward
  • Step-by-step approach:
  • Initialize two pointers:
  • left = 0
  • right = len(numbers) - 1
  • Loop while left < right:
  • Calculate sum = numbers[left] + numbers[right]
  • If sum equals target → return indices
  • If sum < target → move left forward
  • If sum > target → move right backward CODE:
class Solution:
    def twoSum(self, numbers, target):
        left = 0
        right = len(numbers) - 1

        while left < right:
            total = numbers[left] + numbers[right]

            if total == target:
                return [left + 1, right + 1]  # 1-based index

            elif total < target:
                left += 1
            else:
                right -= 1 
Enter fullscreen mode Exit fullscreen mode

How It Works
The algorithm narrows down the search space using two pointers
It avoids checking all pairs
Uses the sorted property to make smart moves

Top comments (0)