Problem 167

Abstract / Summary

Given a sorted array of integers and a target, find two numbers that add up to the target.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0167.py

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        size = len(numbers)
        left = 0
        right = size - 1
        while left < right:
            need = target - numbers[left]
            right = bisect.bisect_left(numbers, need, left + 1, right)
            if right < size and need == numbers[right]:
                return [ left + 1, right + 1 ]

            left += 1

        return None
14 lines | 456 bytes | submitted August 21, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (5+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic β€œtwo-sum” problem for a sorted list of integers. It receives a list numbers and an integer target, and returns a pair of 1-based indices whose corresponding values add up to target. The algorithm leverages the sorted property of the input to reduce the search space dramatically, combining a two-pointer approach with binary search.

Core Logic

The method begins by determining the length of the input list and initializing two pointers, left at the start and right at the end of the array.

size = len(numbers)
left = 0
right = size - 1

A loop runs while the left pointer remains strictly before the right pointer. Inside the loop, the value needed to reach the target from the current left element is computed.

need = target - numbers[left]

Instead of scanning linearly from the current right position, the code invokes the standard library binary search routine bisect_left to locate the smallest index where need could be inserted while preserving order. The search is confined to the sub-range that starts just after left and ends at the current right.

right = bisect.bisect_left(numbers, need, left + 1, right)

If the binary search lands within the bounds of the array and the element at the discovered right index matches need, the method returns the 1-based indices of the two numbers.

if right < size and need == numbers[right]:
    return [ left + 1, right + 1 ]

When a match is not found, the left pointer advances by one, and the loop repeats.

left += 1

If the loop terminates without locating a suitable pair, the function returns None.

return None

Edge Cases

The algorithm gracefully handles several boundary conditions. When the input list contains fewer than two elements, the initial while left < right condition fails immediately, leading to a None result without any further processing. If the target value is smaller than the sum of the two smallest elements, the binary search will always produce an index equal to right or beyond, and the equality check prevents a false positive. Conversely, when the target exceeds the sum of the two largest elements, the binary search will return an index equal to right (the upper bound of the search range), and the subsequent check again avoids an incorrect match. The use of bisect_left with explicit bounds (left + 1, right) ensures that the algorithm never re-examines the same element as both left and right, preserving correctness even when duplicate values appear in the list.

Performance Optimizations

Two primary optimizations are evident. First, the algorithm exploits the sorted nature of the input by narrowing the search interval for each iteration, eliminating the need for a full scan of the right side. This reduces the number of comparisons dramatically compared with a naΓ―ve double-loop approach. Second, the integration of binary search (bisect_left) to locate the complementary value provides a logarithmic lookup within the current window, rather than a linear scan. By updating the right pointer directly with the result of the binary search, the code avoids redundant checks and ensures that each iteration makes maximal progress toward either finding a solution or exhausting the search space. The incremental movement of the left pointer guarantees that each element is considered exactly once as the potential first operand, while the binary search efficiently validates the existence of a matching second operand.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a long row of numbered blocks lined up in a specific order. The goal is to pick two of these blocks that add up to a secret target number.

The code sets up two pointers, which act like plastic fingers. One finger starts at the very beginning of the row, and the other starts at the very end.

The program checks the number under the first finger and calculates how much more is needed to reach the secret target. Instead of looking at every single block one by one, it uses a clever trick to jump directly to where that missing piece might be hiding in the row.

If the number found there completes the set, the task is finished. If the number is too big or too small, the first finger moves one step to the right, and the process repeats. This continues until the correct pair of blocks is found.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.78 | σ = 1.83

Complexity Analysis

Time: loglinear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
fpdjsns C++
gaosq0604 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
chandansgowda Python
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
fpdjsns C++
gaosq0604 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
muhammadfarhankt Go
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
YuriSpiridonov Python
zfang399 C++
51 links | 35 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Two Sum II - Input Array Is Sorted : Explanation βž• Live Coding πŸ§‘πŸ»β€πŸ’» (In Hinglish)'
codestorywithMIK 11 mins
Two Sum II - Input Array Is Sorted : Explanation βž• Live Coding πŸ§‘πŸ»β€πŸ’» (In Hinglish)
YouTube video '[Java] Leetcode 167. Two Sum II - Input array is sorted [Two Pointers #1]'
Eric Programming 6 mins
[Java] Leetcode 167. Two Sum II - Input array is sorted [Two Pointers #1]
YouTube video 'Two Sum II - Input array is sorted  (Leetcode 167) - Medium (Hindi)'
The Hustling Engineer 11 mins
Two Sum II - Input array is sorted (Leetcode 167) - Medium (Hindi)
YouTube video 'Efficiently Solving Leetcode Problem 167: Two Sum II - Input array is sorted'
Engineering Digest 7 mins
Efficiently Solving Leetcode Problem 167: Two Sum II - Input array is sorted
YouTube video 'Two Sum II - Input Array Is Sorted | Leetcode 167 | Two Pointers'
Ayushi Sharma 12 mins
Two Sum II - Input Array Is Sorted | Leetcode 167 | Two Pointers
YouTube video 'two sum ii input array is sorted | two sum 2 | two sum ii leetcode | leetcode 167'
Naresh Gupta 10 mins
two sum ii input array is sorted | two sum 2 | two sum ii leetcode | leetcode 167
YouTube video 'Leetcode 167 Two Sum II - Input Array Is Sorted | 3 Approaches | Live coding session'
Coding Decoded 12 mins
Leetcode 167 Two Sum II - Input Array Is Sorted | 3 Approaches | Live coding session
YouTube video 'LeetCode 167. Two Sum II - Input Array Is Sorted | Medium | Algorithm Explained | C++'
Cherry Coding [IIT-G] 8 mins
LeetCode 167. Two Sum II - Input Array Is Sorted | Medium | Algorithm Explained | C++
YouTube video 'Daily Leetcode #800: Jun 09, 2022 - 167. Two Sum II - Input Array Is Sorted'
Programming Live with Larry 7 mins
Daily Leetcode #800: Jun 09, 2022 - 167. Two Sum II - Input Array Is Sorted
YouTube video '167. Two Sum II - Input Array Is Sorted || NEETCODE 150'
TechWithSaumya 11 mins
167. Two Sum II - Input Array Is Sorted || NEETCODE 150
YouTube video 'Leetcode Solution - 167 Two Sum II - Input Array Is Sorted'
John Leonardo 5 mins
Leetcode Solution - 167 Two Sum II - Input Array Is Sorted
YouTube video 'Leetcode 167 Two Sum II - Input Array Is Sorted (Java)'
TheAnalyticGuy 6 mins
Leetcode 167 Two Sum II - Input Array Is Sorted (Java)
YouTube video '167. Two Sum II - Input Array Is Sorted || Medium || Array  || Cpp'
Komal Pal 9 mins
167. Two Sum II - Input Array Is Sorted || Medium || Array || Cpp
YouTube video 'LeetCode 167: Two Sum II - Input Array Is Sorted | C# Solution | Two-Pointer Technique'
Code Scribbler 8 mins
LeetCode 167: Two Sum II - Input Array Is Sorted | C# Solution | Two-Pointer Technique
YouTube video 'Two Sum II (Input Array is Sorted) - LeetCode #167 - C++'
Sean Chuah 8 mins
Two Sum II (Input Array is Sorted) - LeetCode #167 - C++
YouTube video '10. Leetcode 167. Two Sum II - Input Array Is Sorted : Javascript'
Web Fusion with Bharadwaj 15 mins
10. Leetcode 167. Two Sum II - Input Array Is Sorted : Javascript
YouTube video 'Two Sum II - Input Array Is Sorted - LeetCode 167 - Java'
algobest - Computer Science 6 mins
Two Sum II - Input Array Is Sorted - LeetCode 167 - Java
YouTube video 'Two Sum II Input Array Is Sorted - Google Interview Questions - LeetCode 167 Solution - C++'
nexTRIE 5 mins
Two Sum II Input Array Is Sorted - Google Interview Questions - LeetCode 167 Solution - C++
YouTube video '28. Leetcode 167. Two Sum II - Input Array Is Sorted : JAVA'
Web Fusion with Bharadwaj 14 mins
28. Leetcode 167. Two Sum II - Input Array Is Sorted : JAVA
YouTube video 'Day 199: LeetCode Problem 167. Two Sum II - Input Array is Sorted - Swift'
iOSxBank 11 mins
Day 199: LeetCode Problem 167. Two Sum II - Input Array is Sorted - Swift
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

9 solutions   August 21, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality