#167
Two Sum II - Input Array Is Sorted
MediumArrayTwo PointersBinary SearchTwo PointersArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using the two-pointer technique takes advantage of the sorted nature of the array. We can efficiently find the two numbers by adjusting pointers based on their sum compared to the target.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers, left at the start (index 0) and right at the end (last index) of the array.
- 2Step 2: While left is less than right, calculate the sum of the elements at these pointers.
- 3Step 3: If the sum equals the target, return [left + 1, right + 1]. If the sum is less than the target, increment the left pointer. If the sum is greater, decrement the right pointer.
solution.py13 lines
1# Full working Python code
2
3def two_sum_optimal(numbers, target):
4 left, right = 0, len(numbers) - 1
5 while left < right:
6 current_sum = numbers[left] + numbers[right]
7 if current_sum == target:
8 return [left + 1, right + 1]
9 elif current_sum < target:
10 left += 1
11 else:
12 right -= 1
13ℹ
Complexity note: The time complexity is O(n) because we traverse the array at most once with two pointers. The space complexity is O(1) as we only use a constant amount of space.
- 1The problem can be solved efficiently using the two-pointer technique due to the sorted nature of the input array.
- 2Understanding the relationship between the sum of two numbers and their indices helps in deciding how to move the pointers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.