
Two Sum II β Input Array Is Sorted (Python)
π§ Two Sum II β Input Array Is Sorted (Python) Hi All, Today I solved another interesting problem from LeetCode: Two Sum II β Input Array Is Sorted . π Problem Statement Given a sorted array of integers numbers and a target value, return the indices of two numbers such that they add up to the target. Conditions: Array is 1-indexed (index starts from 1) Array is already sorted (non-decreasing) Exactly one solution exists Cannot use the same element twice Must use constant extra space π‘ Approach πΉ Key Idea: Since the array is sorted , we can use the Two Pointer Technique instead of a hash map. πΉ Steps: Initialize two pointers: left = 0 right = len(numbers) - 1 Calculate sum: If sum == target β return indices If sum < target β move left pointer If sum > target β move right pointer π» Python Code class Solution : def twoSum ( self , numbers , target ): left = 0 right = len ( numbers ) - 1 while left < right : current_sum = numbers [ left ] + numbers [ right ] if current_sum == target : retur
Continue reading on Dev.to Python
Opens in a new tab



