Back to articles
Two Sum & Sorted Two Sum

Two Sum & Sorted Two Sum

via Dev.to PythonJonah Blessy

Problem Statement 1: here The goal is to find two numbers in the list that add up to the given target. Instead of checking every pair, we keep track of the numbers already seen. For each number, we see what value is needed to reach the target. Then check if that required value has already appeared in the list. If it has, the solution is found using the index of those two numbers. If not, store the current number so it can be used for future checks. def two_sum ( nums , target ): seen = {} for i in range ( len ( nums )): needed = target - nums [ i ] if needed in seen : return [ seen [ needed ], i ] seen [ nums [ i ]] = i Problem Statement2: def two_sum ( numbers , target ): left = 0 right = len ( numbers ) - 1 while left < right : s = numbers [ left ] + numbers [ right ] if s == target : return [ left + 1 , right + 1 ] elif s < target : left += 1 else : right -= 1 The array is already sorted, so instead of checking every pair, we can use pointers at the beginning and end. At each step,

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
5 views

Related Articles