Back to articles
Two Sum II - Input Array Is Sorted

Two Sum II - Input Array Is Sorted

via Dev.toJeyaprasad R

In this task, I worked on finding two numbers in a sorted array that add up to a given target value. This problem helped me understand how to efficiently use pointers instead of checking all possible pairs. What I Did I created a function twoSum that takes a sorted list of numbers and a target value. The function returns the positions of the two numbers whose sum equals the target. For example: Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2] This means the numbers at positions 1 and 2 add up to 9. How I Solved It To solve this, I used two pointers: l starting from the beginning of the array r starting from the end of the array Then I checked the sum of the elements at these positions. At each step: If the sum equals the target, I return their positions If the sum is less than the target, I move the left pointer forward If the sum is greater than the target, I move the right pointer backward Code class Solution : def twoSum ( self , numbers : list [ int ], target : int ) -> l

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles