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
Difficulty
and has an acceptance rate of about 66% (5+ million submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Two Pointers
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 1: Two Sum
- problem 653: Two Sum IV - Input is a BST
- problem 1099: Two Sum Less Than K
Solved On The Same Day
- problem 108: Convert Sorted Array to Binary Search Tree
- problem 482: License Key Formatting
- problem 72: Edit Distance
- problem 122: Best Time to Buy and Sell Stock II
- problem 453: Minimum Moves to Equal Array Elements
- problem 515: Find Largest Value in Each Tree Row
- problem 535: Encode and Decode TinyURL
- problem 123: Best Time to Buy and Sell Stock III
Extra
- 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