AlgoMaster Logo

Two Sum II - Input Array Is Sorted

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest way to solve this problem is by checking every possible pair in the array to see if it adds up to the target. Since the array is sorted, once the sum exceeds the target, we can stop checking further elements with the current element.

Code:

2. Two Pointers

Intuition:

Since the array is sorted, we can use a two-pointer technique. Start with one pointer at the beginning and the other at the end of the array. Check the sum of the values at these pointers:

  • If the sum equals the target, return the 1-indexed positions.
  • If the sum is less than the target, move the left pointer to the right to increase the sum.
  • If the sum is more than the target, move the right pointer to the left to decrease the sum.

Code: