Back to articles
Solving Two Sum II (Sorted Array) Using the Two Pointer Technique in Python

Solving Two Sum II (Sorted Array) Using the Two Pointer Technique in Python

via Dev.to PythonSri Mahalakshmi

Introduction In this problem, we need to find two numbers that add up to a given target. Since the array is already sorted, we can use a more efficient approach instead of checking all possible pairs. Problem Explanation You are given: A sorted array of integers ( numbers ) A target value Find two numbers such that their sum equals the target and return their indices using 1-based indexing. Example Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2] Because 2 + 7 = 9 Approach Used – Two Pointer Technique Use two pointers: left at the beginning right at the end Move the pointers based on the sum until the target is found. Code (Python) class Solution : def twoSum ( self , numbers : list [ int ], target : int ) -> list [ int ]: left = 0 right = len ( numbers ) - 1 while left < right : current_sum = numbers [ left ] + numbers [ right ] if current_sum == target : return [ left + 1 , right + 1 ] elif current_sum < target : left += 1 else : right -= 1 Code Explanation (Step by Step) L

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles