Two Sum II - Input Array Is Sorted — LeetCode 167 Python Solution

MediumArrayTwo PointersBinary Search
Problem
#167
Reading time
2 min

The problem

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.

Example

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].

Python solution

Python
class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        n = len(numbers)
        for i in range(n - 1):
            x = target - numbers[i]
            j = bisect_left(numbers, x, lo=i + 1)
            if j < n and numbers[j] == x:
                return [i + 1, j + 1]

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the array `numbers`
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 167. Two Sum II - Input Array Is Sorted is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 167. Two Sum II - Input Array Is Sorted?
LeetCode 167. Two Sum II - Input Array Is Sorted is rated Medium on LeetCode.
What is the time complexity of LeetCode 167. Two Sum II - Input Array Is Sorted?
The Python solution on this page runs in O(n \times \log n), where n is the length of the array `numbers`.
What is the space complexity of LeetCode 167. Two Sum II - Input Array Is Sorted?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 167. Two Sum II - Input Array Is Sorted cover?
LeetCode 167. Two Sum II - Input Array Is Sorted is tagged Array, Two Pointers and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview