Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources
Two Sum II – Input Array Is Sorted

Two Sum II – Input Array Is Sorted

Problem Statement

Given a sorted array of integers and a target sum, find two numbers such that they add up to the target. Return their 1-based indices. This is an easy-level problem solved using two pointers.

Example

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

Output: [1, 2] (2 + 7 = 9, indices are 1-based)

Code

Java
Python
JavaScript
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[] {left + 1, right + 1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[] {}; // No solution found
    }
}
            
def two_sum(numbers, target):
    left, right = 0, len(numbers) - 1
    
    while left < right:
        curr_sum = numbers[left] + numbers[right]
        if curr_sum == target:
            return [left + 1, right + 1]
        elif curr_sum < target:
            left += 1
        else:
            right -= 1
    return []  # No solution found

# Example usage
print(two_sum([2, 7, 11, 15], 9))  # [1, 2]
            
function twoSum(numbers, target) {
    let left = 0, right = numbers.length - 1;
    
    while (left < right) {
        let sum = numbers[left] + numbers[right];
        if (sum === target) {
            return [left + 1, right + 1];
        } else if (sum < target) {
            left++;
        } else {
            right--;
        }
    }
    return []; // No solution found
}

// Example usage
console.log(twoSum([2, 7, 11, 15], 9)); // [1, 2]
            

Explanation

  • Use two pointers: left at the start, right at the end.
  • Calculate the sum of elements at both pointers.
  • If sum equals target, return 1-based indices.
  • If sum is less, move left pointer up; if more, move right pointer down.

Note

Time complexity is O(n) due to a single pass with two pointers. Space complexity is O(1).