Taro Logo

Two Sum II - Input Array Is Sorted

#49 Most AskedMedium
Topics:
ArraysTwo PointersBinary Search

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

Example 1:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2].

Example 2:

Input: numbers = [2,3,4], target = 6
Output: [1,3]
Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3].

Example 3:

Input: numbers = [-1,0], target = -1
Output: [1,2]
Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

Constraints:

  • 2 <= numbers.length <= 3 * 104
  • -1000 <= numbers[i] <= 1000
  • numbers is sorted in non-decreasing order.
  • -1000 <= target <= 1000
  • The tests are generated such that there is exactly one solution.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are the returned indices 1-indexed (as mentioned in the problem description) or 0-indexed?
  2. Can the array contain negative numbers, zeros, or only positive integers?
  3. Are there any duplicate numbers in the array, and how should they be handled?
  4. Can I assume that a valid solution is always guaranteed to exist, or should I handle the case where no such pair is found?
  5. If there are multiple valid pairs that sum to the target, does it matter which one I return?

Brute Force Solution

Approach

Imagine you are given a row of numbers arranged in order from smallest to largest, and you need to find two distinct numbers from that row that add up to a specific target value. The brute force approach involves trying every single possible pair of numbers in the row until you find the pair that hits the target.

Here's how the algorithm would work step-by-step:

  1. Pick the very first number in the row.
  2. Compare it by adding it to the second number, then the third number, then the fourth number, and so on, testing every number that comes after it one by one.
  3. Check each time if the sum of your chosen pair equals the target value you are looking for.
  4. If the sum matches the target, you have found your answer and can stop right there.
  5. If the pair does not match the target, move on to the next number in the row and repeat the entire process of testing it against every number that follows it.
  6. Continue trying every possible combination of two numbers until you discover the correct pair.

Code Implementation

def two_sum(numbers, target):
    # Iterate through every possible first number to test all unique pairs sequentially
    for first_pointer in range(len(numbers)):

        # Test the current number against every subsequent number in the sorted array
        for second_pointer in range(first_pointer + 1, len(numbers)):

            # Check if the sum of the chosen pair exactly matches the required target value
            if numbers[first_pointer] + numbers[second_pointer] == target:
                return [first_pointer + 1, second_pointer + 1]

    return []

Big(O) Analysis

Time Complexity
O(n²) – The brute force approach uses a nested loop structure where the outer loop picks each of the n elements in the array one by one. For every chosen element, the inner loop checks every subsequent element after it to test potential pairs. Specifically, for the first element we test n-1 elements, for the second n-2 elements, and so on. This sums up to approximately n * n / 2 total pair checks, which simplifies to a quadratic time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described in the explanation uses only a few primitive integer variables to keep track of the current indices being tested, without allocating any extra data structures that grow with the input size. Because these constant variables require a fixed amount of extra memory regardless of the input size, the auxiliary space complexity remains constant at O(1).

Optimal Solution

Approach

Since the items are already arranged neatly from smallest to largest, we can find our target pair much faster without testing every single combination. By placing one helper at the very beginning and another at the very end, we can intelligently narrow down our search based on how their combined value compares to our target.

Here's how the algorithm would work step-by-step:

  1. Place your left hand at the very beginning of the line and your right hand at the very end.
  2. Add together the two items your hands are currently touching.
  3. If the combined value matches your target, you have successfully found your answer.
  4. If the combined value is too small, move your left hand one step to the right to increase the total.
  5. If the combined value is too large, move your right hand one step to the left to decrease the total.
  6. Repeat this process of moving your hands inward until they meet or you find the exact match.

Code Implementation

class Solution:
    def twoSum(self, numbers_array: list[int], target_value: int) -> list[int]:
        left_pointer = 0
        right_pointer = len(numbers_array) - 1

        while left_pointer < right_pointer:
            current_sum = numbers_array[left_pointer] + numbers_array[right_pointer]

            # We found the exact pair matching the target sum.
            if current_sum == target_value:
                return [left_pointer + 1, right_pointer + 1]

            # The sum is too small, so advance the left pointer to increase the total.
            elif current_sum < target_value:
                left_pointer += 1

            # The sum is too large, so retreat the right pointer to decrease the total.
            else:
                right_pointer -= 1

        return []

Big(O) Analysis

Time Complexity
O(n) – The cost of this search is driven by the two pointers starting at opposite ends of the array and moving inward toward each other. In the worst-case scenario, every single element in the array of size n is inspected at most once as the pointers step closer. This process visits each element a constant number of times without any nested iterations, resulting in approximately n total operations. Therefore, the linear progression of the pointers simplifies the time complexity to O(n).
Space Complexity
O(1) – The algorithm only uses two pointer variables to track the positions at the beginning and the end of the array. These two pointers require a constant amount of extra memory regardless of the input size N. No additional data structures, temporary lists, or recursive stack frames are created during execution. Therefore, the auxiliary space complexity remains strictly constant as the input array grows.

Edge Cases

Array with exactly two elements
How to Handle:
The two pointers start at index 0 and 1, correctly evaluating the only possible pair immediately.
Negative numbers and zero included in the array
How to Handle:
The two-pointer technique works mathematically with any signed integers because the array is sorted.
All elements are identical
How to Handle:
Pointers will correctly converge on the exact two indices whose sum matches the target.
Maximum-sized inputs with values near integer limits
How to Handle:
Addition could theoretically overflow standard integer bounds, so using 64-bit integers prevents overflow.
Target can only be met by the very first and very last elements
How to Handle:
The left and right pointers start at opposite ends and will evaluate this extreme span on the first iteration.
Target can only be met by adjacent elements in the middle of the array
How to Handle:
The pointers will systematically narrow down from the edges until they meet at the correct adjacent pair.
Problem statement guarantees exactly one solution
How to Handle:
We do not need to handle multiple solutions or missing pairs, allowing the search to terminate instantly upon a match.
Inputs using 1-based indexing as specified
How to Handle:
We must add 1 to the final 0-indexed array positions before returning the result.
0/245 completed