Leetcode Problem 167. Two Sum II - Input Array Is Sorted

167. Two Sum II - Input Array Is Sorted

Leetcode Solutions

Two Pointers Approach

  1. Initialize two pointers: left at the start of the array and right at the end of the array.
  2. Loop while left is less than right: a. Calculate the sum of numbers[left] and numbers[right]. b. If the sum is equal to the target, return [left + 1, right + 1] as the result (since the array is 1-indexed). c. If the sum is less than the target, increment left to move towards a larger sum. d. If the sum is greater than the target, decrement right to move towards a smaller sum.
  3. Since there is exactly one solution, the loop will always return a result.
UML Thumbnail

Binary Search Approach

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...