KatInterview

167. Two Sum II - Input Array Is Sorted

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find two numbers in a 1-indexed array that add up to a specific target. The array is guaranteed to be sorted in non-decreasing order, and there is exactly one solution. A key constraint is that our solution must use only constant extra space.

Solution

Two Sum II - Input Array Is Sorted in Python

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        # Initialize two pointers, one at the start and one at the end.
        left, right = 0, len(numbers) - 1

        # Loop until the pointers cross.
        while left < right:
            current_sum = numbers[left] + numbers[right]
            
            if current_sum == target:
                # Found the pair, return 1-based indices.
                return [left + 1, right + 1]
            elif current_sum < target:
                # Sum is too small, move the left pointer to the right for a larger number.
                left += 1
            else: # current_sum > target
                # Sum is too large, move the right pointer to the left for a smaller number.
                right -= 1
        
        # The problem statement guarantees a solution exists, so the loop will always find one.

Two Sum II - Input Array Is Sorted in Java

class Solution {
    public int[] twoSum(int[] numbers, int target) {
        // Initialize two pointers, one at the beginning and one at the end of the array.
        int left = 0;
        int right = numbers.length - 1;

        // Loop until the two pointers meet.
        while (left < right) {
            int sum = numbers[left] + numbers[right];

            if (sum == target) {
                // Found the solution. Return 1-based indices.
                return new int[]{left + 1, right + 1};
            } else if (sum < target) {
                // The sum is too small, so we need a larger number.
                // Move the left pointer to the right.
                left++;
            } else { // sum > target
                // The sum is too large, so we need a smaller number.
                // Move the right pointer to the left.
                right--;
            }
        }

        // According to the problem description, a solution always exists.
        // So, this part is unreachable. Throw an exception for robustness.
        throw new IllegalArgumentException("No two sum solution");
    }
}

Two Sum II - Input Array Is Sorted in C++

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        // Initialize two pointers, one at the beginning and one at the end of the array.
        int left = 0;
        int right = numbers.size() - 1;

        // Loop until the two pointers meet.
        while (left < right) {
            int sum = numbers[left] + numbers[right];

            if (sum == target) {
                // Found the pair. Return their 1-based indices.
                return {left + 1, right + 1};
            } else if (sum < target) {
                // The sum is too small, so we need a larger number.
                // Move the left pointer to the right.
                left++;
            } else { // sum > target
                // The sum is too large, so we need a smaller number.
                // Move the right pointer to the left.
                right--;
            }
        }

        // According to the problem description, a solution always exists.
        // So, this part is theoretically unreachable.
        // Returning an empty vector as a fallback.
        return {};
    }
};

Two Sum II - Input Array Is Sorted in TypeScript

function twoSum(numbers: number[], target: number): number[] {
    // Initialize two pointers, one at the beginning and one at the end of the array.
    let left = 0;
    let right = numbers.length - 1;

    // Loop until the two pointers meet.
    while (left < right) {
        const sum = numbers[left] + numbers[right];

        if (sum === target) {
            // Found the solution. Return 1-based indices.
            return [left + 1, right + 1];
        } else if (sum < target) {
            // The sum is too small, so we need a larger value.
            // Move the left pointer to the right.
            left++;
        } else { // sum > target
            // The sum is too large, so we need a smaller value.
            // Move the right pointer to the left.
            right--;
        }
    }

    // According to the problem description, a solution always exists,
    // so this line is theoretically unreachable.
    // A return is needed for type safety in some setups, so we return an empty array.
    return [];
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.