Two Sum II - Algorithm Explanation
May 15, 2025 ยท View on GitHub
Problem Description
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return the indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Example
Input:
numbers = [2, 7, 11, 15, 9], target = 16
Algorithmic Steps
The problem is solved using the two pointers technique. The algorithm can be summarized as follows:
-
Initialize Pointers:
- Set the
leftpointer to the start of the array (index0). - Set the
rightpointer to the last index of the array (length - 1).
- Set the
-
Iterate and Calculate:
- Compute the
totalby summing the elements at theleftandrightpointers.
- Compute the
-
Check Conditions:
- If
total == target:- Return the indices
[left + 1, right + 1](convert 0-based indices to 1-based).
- Return the indices
- If
total > target:- Decrement the
rightpointer to reduce thetotal.
- Decrement the
- If
total < target:- Increment the
leftpointer to increase thetotal.
- Increment the
- If
-
Repeat:
- Continue steps 2 and 3 until the two numbers sum up to the
target.
- Continue steps 2 and 3 until the two numbers sum up to the
-
Handle Edge Cases:
- If no such numbers exist that sum to the
target, return[-1, -1].
- If no such numbers exist that sum to the
Time and Space Complexity
-
Time Complexity:
- The algorithm runs in O(n), where
nis the number of elements in the array. This is because we traverse the array at most once.
- The algorithm runs in O(n), where
-
Space Complexity:
- The space complexity is O(1), as only two pointer variables are used, and no additional data structures are required.