DEV Community

Mohammed Azim J
Mohammed Azim J

Posted on

Two Sum II – Input Array Is Sorted

Two Sum II – Input Array Is Sorted
Problem

Now the array is already sorted, and we must use constant extra space.

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

(Note: Index starts from 1)

Best Approach – Two Pointer Technique

Since array is sorted:

If sum is too small → move left pointer
If sum is too large → move right pointer

Algorithm Steps
left = 0
right = n - 1
While left < right:
sum = numbers[left] + numbers[right]
If sum == target → return indices
If sum < target → left++
If sum > target → right--

Python Code
def twoSum(numbers, target):
left = 0
right = len(numbers) - 1

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

    if s == target:
        return [left + 1, right + 1]

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

Complexity
Type Complexity
Time O(n)
Space O(1)

Difference Between Both Problems
Feature Two Sum Two Sum II
Array Unsorted Sorted
Method Hash Map Two Pointer
Space O(n) O(1)
Index 0-based 1-based
Time O(n) O(n)

Top comments (0)