Two Sum II - Input Array Is Sorted
LeetCode 167 · Medium · solution, intuition & step-by-step walkthrough
Sorted ⇒ two pointers squeeze toward the target.
This is how I solved Two Sum II - Input Array Is Sorted (LeetCode 167), a medium problem from the Two Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Because the array is sorted, start with the smallest and largest values. If their sum is too small, the only way up is to move the left pointer right; too big, move the right pointer left.
Approach
- 1
left = 0, right = n − 1.
- 2
Sum equals target → return 1-based indices.
- 3
Sum too small → left += 1; too big → right −= 1.
How I solved it
Two pointersPythonO(n) time · O(1) space
class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
left = 0
right = len(numbers)-1
while left<right:
cur_sum = numbers[left]+numbers[right]
if cur_sum==target:
return [left+1,right+1]
elif cur_sum<target:
left+=1
else:
right-=1
Two Sum II - Input Array Is Sorted — FAQ
What is the intuition behind Two Sum II - Input Array Is Sorted?
Because the array is sorted, start with the smallest and largest values. If their sum is too small, the only way up is to move the left pointer right; too big, move the right pointer left.
How do you solve Two Sum II - Input Array Is Sorted (LeetCode 167)?
1. left = 0, right = n − 1. 2. Sum equals target → return 1-based indices. 3. Sum too small → left += 1; too big → right −= 1.
What is the time and space complexity of Two Sum II - Input Array Is Sorted?
Time: O(n). Space: O(1). (Accepted approach: Two pointers.)
What are common mistakes in Two Sum II - Input Array Is Sorted?
The answer is 1-indexed.