Back to articles
Two Sum II – Input Array Is Sorted (Python)

Two Sum II – Input Array Is Sorted (Python)

via Dev.to PythonManoj Kumar

🧠 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

Read Full Article
2 views

Related Articles