MediumNo. 0167

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

Topics
Array, Two Pointers, Binary Search
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

PythonSolution
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

Time
O(n × log n)where n is the length of the array `numbers`
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
0001Two SumEasy
0475HeatersMedium
0658Find K Closest ElementsMedium
0719Find K-th Smallest Pair DistanceHard
0786K-th Smallest Prime FractionMedium
0825Friends Of Appropriate AgesMedium

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

Free to download. Check it runs on your machine, then pick a plan.