
Two Sum (Sorted Array)
In this task, I worked on finding two numbers in a sorted array that add up to a given target. The goal is to return their 1-based indices. What I Did I implemented a function twoSum that takes: a sorted array numbers a target value and returns the indices of the two numbers whose sum equals the target. Example: Input: numbers = [2, 7, 11, 15], target = 9 Output: [1, 2] Explanation: 2 + 7 = 9 → indices are 1 and 2 How I Solved It Instead of brute force (O(n²)), I used the Two Pointer Technique. Core Idea: Since the array is sorted: If sum is too small → move left pointer forward If sum is too large → move right pointer backward Step-by-step approach: Initialize two pointers: left = 0 right = len(numbers) - 1 Loop while left < right: Calculate sum = numbers[left] + numbers[right] If sum equals target → return indices If sum < target → move left forward If sum > target → move right backward CODE: class Solution : def twoSum ( self , numbers , target ): left = 0 right = len ( numbers ) -
Continue reading on Dev.to Python
Opens in a new tab



